jQuery无法在AJAX函数中定义变量
我在修改AJAX函数中的任何变量时遇到困难 如果我有一个外部变量,让我们说jQuery无法在AJAX函数中定义变量,jquery,ajax,variables,Jquery,Ajax,Variables,我在修改AJAX函数中的任何变量时遇到困难 如果我有一个外部变量,让我们说 var myName=“我的名字是肯尼” 在AJAX函数中,我是这样做的 myName.replace(“肯尼”、“伯爵”) 在AJAX函数之后执行console.log(myName)时,我会得到“我的名字是Kenny”,就好像什么都没发生一样 以下是一个例子: var actorId; var castListUrl = 'http://api.themoviedb.org/3/person/id/movie_cre
var myName=“我的名字是肯尼”代码>
在AJAX函数中,我是这样做的
myName.replace(“肯尼”、“伯爵”)代码>
在AJAX函数之后执行console.log(myName)
时,我会得到“我的名字是Kenny”,就好像什么都没发生一样
以下是一个例子:
var actorId;
var castListUrl = 'http://api.themoviedb.org/3/person/id/movie_credits?api_key=###';
//start ajax request
$.ajax({
url: "http://api.themoviedb.org/3/search/person?api_key=###&query=" + actorsName,
//force to handle it as text
dataType: "text",
success: function (data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
actorId = json.results[0].id;
castListUrl = castListUrl.replace("id", "1245");
console.log(castListUrl); // This returns 'http://api.themoviedb.org/3/person/1245/ movie_credits?api_key=###' with **ID** being changed
//now json variable contains data in json format
//let's display a few items
$('#results').html('The actors name is ' + json.results[0].id);
}
});
console.log(castListUrl); // This returns 'http://api.themoviedb.org/3/person/id/movie_credits?api_key=###' without **ID** being changed
我一直在阅读关于jQuery作用域的文章,我不知道我做错了什么。AJAX请求是异步的:一旦发出请求,代码将继续执行,而不等待响应。当响应到达时,将调用更新变量的响应回调
这意味着在AJAX响应回调之前执行console.log
。如果将其移动到回调中,您将看到更新的值 AJAX是异步的。它将在其他代码完成后运行(如果下载需要一段时间,则可能需要很长时间)。您需要将代码重新构造为事件驱动的。