gpt4 book ai didi

javascript - 如何在匿名函数javascript中实现函数的不同行为

转载 作者:行者123 更新时间:2023-12-03 01:45:24 26 4
gpt4 key购买 nike

我是 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"); });

这可能吗?

最佳答案

有多种方法可以实现此目的,但如果我们只是从您的基本要求开始,您可以让 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);
});

关于javascript - 如何在匿名函数javascript中实现函数的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com