【问题标题】:How to check whether my XMLHttpRequest post method success or not?如何检查我的 XMLHttpRequest 发布方法是否成功?
【发布时间】:2019-04-30 07:41:21
【问题描述】:

我不太习惯使用 API。我编写了一个函数,我在其中向 API 发送数据。我在文本框文本更改事件上调用了这个函数。我不知道它是否工作,因为我没有收到任何错误。下面是函数:

function sendAPIData(url,introduction,coordinateid){
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://192.168.51.212:3368/casigo/sDAGinput",true);
    xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    var input = JSON.stringify({
      "coordinate": coordinateid,
      "url": url,
      "introduction": introduction
    });
    xhttp.send(input);
}

它应该返回一些输入字符串。

【问题讨论】:

    标签: javascript json api http


    【解决方案1】:

    要检查服务器的响应,可以使用回调函数:

    function sendAPIData(url,introduction,coordinateid) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "http://192.168.51.212:3368/casigo/sDAGinput",true);
        xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        var input = JSON.stringify({
          "coordinate": coordinateid,
          "url": url,
          "introduction": introduction
        });
    
        // callback function
        xhttp.onload = function(res) {
          if (xhttp.readyState === 4) {
            if (xhttp.status === 200) {
              console.log("OK");
            } else {
              console.error("ERROR");
            }
          }
        };
    
        xhttp.send(input);
    }
    

    xhttp.onload 是一个在 XMLHttpRequest 完成后将被调用的函数。它的参数res 是服务器的响应。

    【讨论】:

      【解决方案2】:

      XMLHttpRequest 包含statusreadyState 属性,可通过onreadystatechange 事件使用。类似下面的代码应该可以工作。

      xhttp.onreadystatechange=function(){
         //readyState == 4 means the request is done and a response is received from the server
      
         if (xhttp.readyState==4 && xhttp.status==200 && typeof(xhttp.responseText) == 'string'){
            //Do something          
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 2011-01-21
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多