我目前正在将网页移到SPA(单页应用程序)上,这样做的时候,我现在只处理一个HTML页面,该页面使用JS填充(就像普通SPA应该做的那样)。因此,这(出于方便起见)意味着我将JS文件缩减为一个文件(也许是个好主意,也许是个坏主意-我们将会看到,但这不是重点)。我决定制作一个“黑匣子” AJAX请求处理程序,以最小化代码。这是我遇到意料之外的问题的地方。代码是(该示例click
用于我的登录屏幕):
function ajaxCall(type, url, data, dataType) {
$.ajax({
type: type,
url: url,
data: data,
dataType: dataType,
})
.done(function(xhr) {
return xhr;
})
.fail(function(xhr, status, errorThrown) {
console.log('AJAX call error: ' + errorThrown);
console.dir(xhr);
})
.always(function(xhr, status) {
console.log('AJAX call status: ' + status);
});
}
var res;
//this is inside $(document).ready - I just skipped some lines
$(document).on('click', '#submit', function(e) {
res = ajaxCall('POST', '/Login', { 'username': $('#username').val(), 'password': $('#password').val() }, 'json');
console.log('res =', res); // this is where the problem was discovered
});
(你们中有些人已经吟了)当然,当我对此进行测试时,我在控制台中得到的是res = undefined
。
我花了几个小时研究这个问题,并弄清了为什么会发生。这些是我为解决这个问题而研究的一些页面:1 2 3
切入正题:问题是我没有使用Promise
。收到。我可以解决。我似乎无法解决的问题是使用Promise
带有jQuery AJAX请求的普通JS 。
我已经走了这么远:
function ajaxCall(type, url, data, dataType) {
return Promise.resolve($.ajax({
type: type,
url: url,
data: data,
dataType: dataType,
}));
}
但我无法弄清楚如何将的其它特性/功能promise
,分别是:.then() and .reject()
。据我了解,上述承诺将自动解决,但是如果需要被拒绝怎么办?也许我还在考虑jQuery的.done(), .fail() and .always()
。
但是,尽管我做了很多谷歌搜索,但终生无法找到如何将纯JS的所有功能
Promise
与jQuery AJAX请求完全结合在一起的方法。
因此,我要向stackoverflow社区寻求有关此问题的见解。
谢谢你。
因此,Promise
您不是真正的救星。您遇到的问题是,console.log('res =', res);
在使用.done()
和.fail()
方法完成AJAX请求后,您需要调用。
function ajaxCall(type, url, data, dataType) {
return $.ajax({
type: type,
url: url,
data: data,
dataType: dataType,
});
}
//this is inside $(document).ready - I just skipped some lines
$(document).on('click', '#submit', function(e) {
var res = ajaxCall('POST', '/Login', { 'username': $('#username').val(), 'password': $('#password').val() }, 'json');
res.done(function (data) {
console.log('res =', data);
});
});
如果您真的想使用real Promise
,则可以执行以下操作
function ajaxCall(type, url, data, dataType) {
return new Promise(function (resolve, reject) {
$.ajax({
type: type,
url: url,
data: data,
dataType: dataType,
}).done(function (data) {
resolve(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
reject(errorThrown);
});
});
}
//this is inside $(document).ready - I just skipped some lines
$(document).on('click', '#submit', function(e) {
var res = ajaxCall('POST', '/Login', { 'username': $('#username').val(), 'password': $('#password').val() }, 'json');
res.then(function (data) {
console.log('res = ', data);
}).catch(function (err) {
console.error(err);
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句