2017-06-02 66 views
0

我想知道是否有可能使用JavaScript进行GET请求,因此它可以在不刷新页面的情况下更新文本。是否可以通过javascript获取请求?

如果这是可能的,我怎样才能使用JavaScript获取请求&得到结果/从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; 
} 

而且,它完全停止主线程,使网站无法响应。哪里不对?

+1

千万不要错过'FALSE'为['xmlHttp'(https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open) –

+1

是异步设置为假(第三个分页ram of'.open'),所以它会锁定用户界面直到它完成。您的代码需要修改才能使用async true。 – James

+0

是的 - 但为什么需要aysnc来获取数据?这不是我担心的表现,即使它应该在主线程中,脚本仍然无法正常工作。 – JavaC3code

回答

1

当前,您将async参数设置为false,以便将请求发送到服务器,并且浏览器等待响应。为了使一个异步请求,就像THRID PARAM 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的文档

注:与壁虎30.0开始(火狐30.0/30.0雷鸟/ SeaMonkey的2.27),第m同步请求ain线程已被 弃用,这是由于对用户体验的负面影响。

+0

他还需要将使用'responseText'的代码移到回调函数中。 – Barmar

0

如果你想使用异步你需要一些代码的修改,即发生在响应完成后需要是在一个回调函数如下东西:

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

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

OR的jQuery ...

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