function foo(dataString){
var jqXHR = $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
return 1;
}
}
});
return jqXHR.responseText;
}
如何获取 foo 返回的 responseText?
使用
(在另一个 jQuery 事件中) var 结果 = foo(dataString); 不起作用。
结果仍然是未定义的。
最佳答案
最好使用回调来完成您想要做的事情。
var uiHelper = function () {
var cachedText= {};
var getText = function (options) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="options" type="object">options{url:The url to the file with the HTML,successCallback:function,errorCallback:function,isAsync:true||false,cache:true|false}</param>
function xhrSuccess() {
if (this.cache) { cachedText[this.url] = this.responseText; };
if (this.successCallback) {
this.successCallback.apply(this.responseText, this.arguments);
} else {
return cachedText[this.url];
};
};
function xhrError() {
if (this.errorCallback) {
this.errorCallback.apply(this.statusText);
} else {
return this.statusText;
};
};
if (!cachedText[options.url]) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", options.url, options.isAsync);
xmlhttp.cache = options.cache || false;
xmlhttp.url = options.url;
xmlhttp.onload = xhrSuccess;
xmlhttp.onerror = xhrError;
xmlhttp.successCallback = options.successCallback || undefined;
xmlhttp.errorCallback = options.errorCallback || undefined;
xmlhttp.send();
} else {
if (options.successCallback) {
options.successCallback.apply(cachedText[options.url], this.arguments);
} else {
return cachedText[options.url];
};
};
};
return {
getText: getText
};
}();
-----用法-----
var successCallBack = function () {
}
var errorCallBack= function () {
}
uiHelper.getText(
{
url: 'url',
successCallBack: successCallBack,
errorCallBack: errorCallBack,
isAsync: true,
cache: false
})
关于javascript - 在 jQuery/AJAX 中获取函数的responseText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887422/