可以使用 javascript 获取请求吗?

Is a get request possible with javascript?

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

如果可行,我如何使用 javascript 发出获取请求并从 json 获取 result/decode?

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

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;
}

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

当前你设置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 文档的注释

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

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

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);

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