Javascript Ajax请求在调用后未设置全局变量
我试图在Javascript中进行AJAX调用,以获得两个值。然后我想全局使用这些值进行一些计算,然后打印出结果。以下是我的代码Javascript Ajax请求在调用后未设置全局变量,javascript,ajax,variables,global-variables,Javascript,Ajax,Variables,Global Variables,我试图在Javascript中进行AJAX调用,以获得两个值。然后我想全局使用这些值进行一些计算,然后打印出结果。以下是我的代码 // my calculation functions will go here var value1 = 0; var value2 = 0; MakeRequest(); //after makeRequest() value1 and value2 should be 10 and 20 respectively. var tot
// my calculation functions will go here
var value1 = 0;
var value2 = 0;
MakeRequest(); //after makeRequest() value1 and value2 should be 10 and 20 respectively.
var total = value1 + value2;
console.log(total); // this is still zero. because value1 and value2 are still 0.
//request AJAX
function createXMLHTTPObject(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// IE 7+, Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
return ajaxRequest;
} catch (e){
// Internet Explorer
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
return ajaxRequest;
} catch (e) {
try{
// Internet Explorer 5, 6
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
return ajaxRequest;
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
// Create a function that will receive data sent from the server
function AjaxRequest(url,callback,method){
var req = createXMLHTTPObject();
req.onreadystatechange= function(){
if(req.readyState != 4) return;
if(req.status != 200) return;
callback(req);
}
req.open(method,url,true);
req.send(null);
}
function AjaxResponse(req){
var respXML=req.responseXML;
if(!respXML) return;
value1=respXML.getElementsByTagName("value1")[0].childNodes[0].nodeValue;
value2= respXML.getElementsByTagName("value2")[0].childNodes[0].nodeValue;
console.log("the value1 is "+ value1); //successfully print the values
console.log("the value2 is "+ value2);
}
function MakeRequest(){
AjaxRequest("values.xml",AjaxResponse,"get");
}
因为AJAX调用是异步的,这意味着您的代码实时运行如下:
var value1 = 0;
var value2 = 0;
MakeRequest(); // AJAX REQUEST is made, that will happen on its on timeline
var total = value1 + value2;
console.log(total); // still will be 0 at this point, since AJAX response has not returned
// MakeRequest will fire AJAX request and WHEN THE REQUEST IS SUCCESSFUL, it can modify value1 and value2, then calculate total
如果希望
value1
和value2
依赖于AJAX请求的结果,则应在AJAX请求成功返回后计算total=value1+value2
。因为AJAX调用是异步的,这意味着您的代码实时运行如下:
var value1 = 0;
var value2 = 0;
MakeRequest(); // AJAX REQUEST is made, that will happen on its on timeline
var total = value1 + value2;
console.log(total); // still will be 0 at this point, since AJAX response has not returned
// MakeRequest will fire AJAX request and WHEN THE REQUEST IS SUCCESSFUL, it can modify value1 and value2, then calculate total
如果希望value1
和value2
依赖于AJAX请求的结果,则应在AJAX请求成功返回后计算total=value1+value2
。AJAX中的A代表“异步”。调用MakeRequest()
不会阻塞。AJAX中的A代表“异步”。调用MakeRequest()
不会阻塞。