每次最终作为未定义的函数返回函数的响应!!
var result = Checkusers();(result is undefined)
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
var obj = eval('(' + response.d + ')');
return obj;
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
我将此功能称为
var Result = CheckUser();
if(Result== false){
//do something
} else{
//do something
}
过去一天我一直在努力!我在一节中读到,这是因为“Ajax是异步的”。 。但我怎么能处理呢?
答案 0 :(得分:1)
您最好将回调函数传递给CheckUser
function CheckUser(callback) {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
var obj = eval('(' + response.d + ')');
callback(obj);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
callback(null);
}
});
}
然后你会这样调用这个函数
CheckUser(function (res) {
if (res === null) {
//false
} else {
//true
}
});
答案 1 :(得分:0)
错字
Checkusers -with s
CheckUser() - 没有s
答案 2 :(得分:0)
更改
datatype:'jsondata'
到
dataType: "json"
由于ajax是异步的,你不能像这样返回数据。你需要在ajax的成功处理程序上编写东西
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
success: function (response) {
//do your stuff here
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
如果要从ajax返回数据,则应使用async : false
作为
function CheckUser() {
var EmpName = $("#txtName").val();
var CheckUser;
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
// ...
success: function (jsonData) {
CheckUser = jsonData
}
});
return CheckUser
}
但它不是一个好方法,它会冻结浏览器
答案 3 :(得分:0)
函数CheckUser()没有任何return语句,这就是为什么你的结果总是未定义的。
将回调传递给您的函数,并在您的ajax调用成功或错误时调用它。
类似的东西:
function CheckUser(callback) {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
success: function (response) {
console.log(response.d);
var obj = eval('(' + response.d + ')');
callback(null, obj);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
callback(response);
}
});
}
然后:
var Result = CheckUser(function ( err, data) {
// check if no err then process whatever data format you have
});