我是JavaScript的新手,我想使用两次send_request函数,但使用不同的行为。名为button1的元素应显示对该元素的响应,而button2则不显示。
function send_request(url) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send('data=test');
xhr.onload = function () {document.getElementById('reply').innerHTML = xhr.responseText;};
}
document.getElementById('button1').addEventListener('click', function() { send_request("/data.php"); });
document.getElementById('button2').addEventListener('click', function() { send_request("/clear_data.php"); });有可能吗?
发布于 2018-06-03 06:32:41
你可以给send_request另一个参数,一个用responseText调用的函数,这样你就可以传递一个赋值给reply的函数,而另一个函数可以做任何你想做的事情:
function send_request(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send('data=test');
xhr.onload = () => callback(xhr.responseText);
}
document.getElementById('button1').addEventListener('click', function() {
send_request("/data.php", (responseText) => {
document.getElementById('reply').innerHTML = responseText;
});
});
document.getElementById('bitton2').addEventListener('click', function() {
send_request("/clear_data.php", (responseText) => {
console.log('bitton 2 response: ' + responseText);
});
});发布于 2018-06-03 06:32:10
有许多方法可以实现这一点,但是如果我们从您的基本需求开始,您可以让send_request简单地接受一个参数,以确定元素是否应该显示响应。
function send_request(url, showResponse) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send('data=test');
xhr.onload = function () {
// If showResponse is true, log the response. If not, don't
showResponse ? document.getElementById('reply').innerHTML = xhr.responseText : null;
};
}
document.getElementById('button1').addEventListener('click', function() {
// Call the function and indicate that the response should be shown
send_request("/data.php", true);
});
document.getElementById('bitton2').addEventListener('click', function() {
// Call the function and indicate that the response should not be shown
send_request("/clear_data.php", false);
});https://stackoverflow.com/questions/50661689
复制相似问题