JQM - 如何使用XMLHttpRequest加载页面时获取动态数据?

时间:2014-01-17 19:35:48

标签: javascript jquery ajax jquery-mobile

我使用pageinit加载页面。我在服务器端使用RESTful API调用XMLHttpRequest向Linux上的PHP程序发送和获取请求。服务器端接受我发送给它的数组并回送JSON。一切都运作良好。但是,HTTP_GET函数返回页面并在完成之前显示内容并从服务器获得响应。

如何防止它在响应之前回复?

pageinit

$(document).on("pageinit","#quote_open1",function(){

             alert('pageinit quote_open1');
             openPage(); });

openPage

function openPage(url, jsontest){
    var jsonResponse=HTTP_GET( url, jsontest);
          alert('!!!!!!!!!!!!!!!!-->'+jsonResponse);
}

HTTP_GET

function HTTP_GET( url, jsonToSend){

   alert('START HTTP_GET');

   var jsonResponse;

    //send get request to server
    xhr = new XMLHttpRequest(); 
    xhr.open("GET",url+"jsonToSend",true);  //open server connection                
    xhr.send();//this is where json string will be sent out
   //  
    //this function send 

    xhr.onreadystatechange = function() 
      {
    if (xhr.readyState == 4)  //read server response
            {
            alert(xhr.readyState);
            jsonResponse=xhr.responseText;
            alert("!!!jsonResponse="+jsonResponse);
            alert("!!!xhr.responseText"+xhr.responseText);

            return "server returned a response 1"; //RETURNS this all the time
            }
        };  
   alert('END HTTP_GET');
   if (xhr.readyState == 4) return  "server returned a response 2"; //want to return this when leaves this function
   return "stil in progress returns before it's finished";
};

(这3个函数在不同的js中)

感谢。

1 个答案:

答案 0 :(得分:0)

你在这里想到的是xhr是异步的事实,所以你的函数HTTP_GET在请求完成之前返回。

你可以使用这样的回调函数:

  $(document).on("pageinit","#quote_open1",function(){

             console.log('pageinit quote_open1');
             openPage(); });



function openPage(){

var doTheJob = function(jsonResponse){ console.log('jsonResponse : '+jsonResponse); }

    HTTP_GET( url, doTheJob);

}

function HTTP_GET( url,callBackFunc){

   console.log('START HTTP_GET');

   var jsonResponse;

    //send get request to server
    xhr = new XMLHttpRequest(); 
    xhr.open("GET",url,true);  //open server connection                

    xhr.onreadystatechange = function() 
      {
    if (xhr.readyState == 4)  //read server response
            {


            callBackFunc(xhr.responseText);
            }
        }; 
   xhr.send();//this is where json string will be sent out
   //  

   console.log('END HTTP_GET');
};