这是我的代码
var jsonpath;
function loginFromDef() {
var a = grantAccess($('#login :input').serialize());
if (a.Msg) {
$('#msg').html(a.Msg).attr('class', 'error');
}
else if (a.done) {
var returnUrl = getQueryString('ReturnURL');
if (returnUrl)
window.location = returnUrl;
else
window.location = 'Home.aspx';
}
return false;
}
function grantAccess(dataToPost) {
$.ajax({
type: "POST",
url: jsonpath + 'Json.ashx?method=GrantAccess',
async: false,
data: dataToPost,
success: function (data) {
return data;
}
});
}
function getQueryString(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Run Code Online (Sandbox Code Playgroud)
var jsonPath正在Default.aspx页面中定义,我loginFromDef()在onclick提交按钮的事件上调用函数.
我收到错误TypeError: a is undefined
不要担心我的.ashx处理程序.它工作正常.我试试看.
我认为var a功能loginFromDef尚未初始化.因为may be jQuery is making asynchronous call. Even I have set async:false在选项中.
我错了.. ?? 请为此建议解决方案.
你没有任何退货声明grantAccess.回调内的return语句没有任何影响(因为它是由$.ajax内部调用的).
Ajax调用是同步的,但您不会从中返回任何数据grantAccess.
你可以这样做:
return $.ajax({
type: "POST",
url: jsonpath + 'Json.ashx?method=GrantAccess',
async: false,
data: dataToPost,
}).responseText;
Run Code Online (Sandbox Code Playgroud)
也许你必须$.parseJSON在返回该值之前使用它.
$.ajax返回一个jqXHR对象,您可以在文档中找到更多信息.
但是,我强烈建议不要使用同步Ajax调用,我没有看到任何理由为什么你需要它.同步请求可能会阻止浏览器(包括其UI),直到收到响应,使浏览器无响应,从而导致糟糕的使用体验.
更改您的代码,以便您可以使用回调来处理响应.例如:
function loginFromDef() {
grantAccess($('#login :input').serialize()).done(function(a) {
if (a.Msg) {
$('#msg').html(a.Msg).attr('class', 'error');
}
else if (a.done) {
var returnUrl = getQueryString('ReturnURL');
if (returnUrl)
window.location = returnUrl;
else
window.location = 'Home.aspx';
}
});
return false;
}
Run Code Online (Sandbox Code Playgroud)
其中grantAccess只返回返回的jqXHR对象$.ajax:
function grantAccess(dataToPost) {
return $.ajax({
type: "POST",
url: jsonpath + 'Json.ashx?method=GrantAccess',
data: dataToPost
});
}
Run Code Online (Sandbox Code Playgroud)