我有一个 Ajax 请求,成功后会更改输入字段的内容。该输入字段会在更改时触发另一系列 Ajax 请求。该代码可以工作,但根据 Chrome 中的控制台,有报道称“主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响”。此错误消息似乎表明正在发出同步请求。
代码如下:
$.ajax({
type: 'GET',
url: '/widgets/test',
async: true,
success: function (response) {
$("#widgetData").val(JSON.stringify(response));
$("#widgetData").trigger("change");
},
error: function (xhr, textStatus, errorThrown) {
console.log("There was a problem requesting the widget endpoint!");
}
});
$("#widgetData").change(function () {
var obj = jQuery.parseJSON($("#widgetData").val());
$.each(obj, function (id, url) {
$("#mainContent").append("<div class='widget' id='widget" + id + "'></div>");
$("#widget" + id).load(url);
});
});
我希望所有请求都是异步的,并且相信我所编写的内容应该可以完成该任务。请帮助我确定出了什么问题,以及为什么我会收到上述错误!
最佳答案
您的第一个 ajax
请求似乎将 async
标志设置为 false
。您可以将该调用更改为以下
$.ajax({
type: 'GET',
async: true,
url: '/widgets/test',
success: function (response) {
$("#widgetData").val(JSON.stringify(response));
$("#widgetData").trigger("change");
},
error: function (xhr, textStatus, errorThrown) {
console.log("There was a problem requesting the widget endpoint!");
}
});
这应该可以修复您的警告消息
关于javascript - 多个 Ajax 调用似乎被视为同步请求,而实际上它们不应该被视为同步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33385011/