簡體   English   中英

如何在匿名函數javascript中實現函數的不同行為

[英]How to implement different behavior for function in anonymous function javascript

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

您可以給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);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM