gpt4 book ai didi

javascript - Ajax请求调用后未设置全局变量

转载 作者:行者123 更新时间:2023-11-28 16:04:41 24 4
gpt4 key购买 nike

我正在尝试在 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 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");
}
  1. 所以我的第一个问题是为什么total = value 1 + value2仍然是0。我将它们设为全局变量,然后在makeRequest()内部更新了value1和value2,但它似乎不影响该值。我该怎么做才能更新 value1 和 value2 以便在这些函数之外使用它们。

  2. 基本上我从在线教程中复制了ajax请求代码。这里有一件事我不明白。当我调用 MakeRequest() 函数时,它调用 AjaxRequest("values.xml",AjaxResponse,"get");然而,AjaxReponse(req) 在这里需要一个参数“req”。但是 AjaxRequest("values.xml",AjaxResponse,"get") 内部的 AjaxResponse 没有放置参数。它仍然有效。这是为什么?我确实理解这部分。

最佳答案

因为 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

total = value1 + value2如果您想要的话,应该在 AJAX 请求成功返回之后计算 value1value2取决于 AJAX 请求的结果。

关于javascript - Ajax请求调用后未设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15581810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com