我有一个问题,当我进行 ajax 调用时,在成功函数中我得到了 json 数据,我不能在成功函数中使用它
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function (response) {
getData[name] = response;
}
});
alert(getData[name]);
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在 ajax 调用中使用 getData
问题是默认 Ajax 请求是异步的
,这意味着 ajax 将启动请求然后执行:alert(getData[name]);然后在后台完成请求并调用成功函数。
所以实际上警报将在成功功能之前执行。并做你想做的事情,你必须告诉 ajax 在它完成之前不要执行任何事情,在其他病房设置async: false
第二件事你必须在 ajax 范围之外声明变量,以便你可以在 ajax 之外访问它
最终代码将是:
var getData;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
async: false,
success: function (response) {
getData[name] = response;
}
});
alert(getData[name]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27938 次 |
| 最近记录: |