【问题标题】:XHRHttpRequest complete functionXHRHttpRequest 完整功能
【发布时间】:2014-12-14 19:36:51
【问题描述】:

当 XHRHttpRequest 完成或返回响应秒时,我如何调用函数。 不使用 jquery。

xmlhttp = new XMLHttpRequest();
xmlhttp.success()

这种每次请求都会调用的函数

【问题讨论】:

  • 那将是onreadystate 等,并且在每个 ajax 教程中都有解释,您所要做的就是在 Google 上搜索 XMLHttpRequest。
  • 你可能想看看this question,然后为每个发送的请求添加一个加载/错误处理程序。

标签: javascript xmlhttprequest


【解决方案1】:

您可以使用以下代码。

var ajaxRequest;  

try{
    // Opera 8.0+, Firefox, Safari, Chrome
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            console.log('something went wrong. Check the error! '+ e);              
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        var response = ajaxRequest.responseText;
       // do something here with the response object
       // you could JSON.parse to parse the response if it is json string
    }
}
ajaxRequest.open("GET", "get_data.php", true); // true for asynchronous request
ajaxRequest.send(null);   // initiate a send(call) 

【讨论】:

  • 我需要的是在每次 ajax 调用完成后运行的回调,而不是针对特定/单个请求。
  • 您发送的每个请求都会调用它。 ajaxRequest.open("GET", "get_data.php", true); ajaxRequest.send(null); // 另一个调用 ajaxRequest.open("GET", "get_response.php", true); ajaxRequest.send(null);等等。你可以改变url,回调就会被执行。
【解决方案2】:
xmlhttp.onreadystatechange = function(){
     if(request.status===200){
         var response = xmlhttp.responseText;
         //do something with response
     }
}

【讨论】:

  • 那么仅仅将 Asynchronous Javascript 和 XML 转换为 Synchronous 是解决方案吗?这几乎是你能做的最糟糕的事情!
  • 已经在编辑..并编辑了我的答案..是的,这正是任何人都可以做的最糟糕的事情:)
  • 我不想发送任何请求,我只想设置一个函数在每个现有请求之后执行,就像 ajaxComplete() 但没有 jquery
  • @YoushaRizvi .. 再次编辑它.. 只需使用 xmlhttp.onreadystatechange 函数,它是请求状态更改时的回调。只需检查状态和 readyState(optional) 就可以开始了.. 无需使用 jQuery
  • 但这必须为每个请求添加,它不是一个全局 ajax 处理程序,这正是 Yousha 所要求的。
猜你喜欢
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 2017-02-20
  • 1970-01-01
相关资源
最近更新 更多