【问题标题】:Is a get request possible with javascript?是否可以使用 javascript 获取请求?
【发布时间】:2017-06-02 21:08:46
【问题描述】:

我想知道是否可以使用 javascript 发出 GET 请求,这样它就可以在不刷新页面的情况下更新文本。

如果可能的话,我如何使用 javascript 发出 get 请求并从 json 获取结果/解码?

我从过去的问题中尝试过这个:

function updateButton(){

    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", false);
    xmlHttp.send(null);
    document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
}

而且,它完全停止了主线程,使网站无响应。怎么了?

【问题讨论】:

  • 不要将false 传递给xmlHttp
  • Async 设置为 false(.open 的第三个参数),因此它将锁定 UI 直到完成。您的代码需要修改才能使用 async true。
  • 是的 - 但是为什么需要 aysnc 来获取数据?我担心的不是性能,即使它应该在主线程上,脚本也无法正常工作。
  • 不管GET还是POST;需要 async 以在等待服务器回复时不要让 JS 戛然而止。不过,你能澄清一下问题是什么吗?网站是否在短时间内无响应?还是完全崩溃了?
  • AJAX 请求应该是异步的。先解决这个问题。之后有什么问题吗?

标签: javascript php frontend backend


【解决方案1】:

当前您将 async 参数设置为 false,因此请求被发送到服务器并且浏览器等待响应。要发出异步请求,只需将 true 作为第三参数传递给 open

xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);

除此之外,您还必须注册一个回调,它等待响应(并且可能处理错误..)

xmlHttp.onload = function (e) {
    if (xmlHttp.readyState === 4) {
        if (xmlHttp.status === 200) {
            console.log(xmlHttp.responseText);
        } else {
           console.error(xmlHttp.statusText);
        }
    }
};
xmlHttp.onerror = function (e) {
    console.error(xmlHttp.statusText);
};

除此之外,来自 mozilla 文档的注释

注意:从 Gecko 30.0 开始(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27),主线程上的同步请求已经 由于对用户体验的负面影响而被弃用。

【讨论】:

  • 他还需要将使用responseText的代码移动到回调中。
【解决方案2】:
var isAjax=false;
function updateButton(){
     if(!isAjax) { //Stops the user making a million requests per minute
        isAjax=true;
        var xmlHttp = null;

        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
        xmlHttp.send(null);
        document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
        isAjax=false;
    }
}

或者 jQuery...

$("#btnUpdate").click(function(){
    $.get("http://xxxx.com/getSpecialSale.php", function(data, status){
        $("#dicebutton").html(data);
    });
});

【讨论】:

    【解决方案3】:

    如果你想使用异步,你将需要一些代码修改,即响应完成后发生的事情需要在回调函数中,如下所示:

    function updateButton(){
    
        var xmlHttp = null;
    
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
        xmlHttp.onload = function () {
          document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
        };
        xmlHttp.send(null);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      相关资源
      最近更新 更多