Home  >  Article  >  Web Front-end  >  Ajax执行顺序流程及回调问题分析_基础知识

Ajax执行顺序流程及回调问题分析_基础知识

WBOY
WBOYOriginal
2016-05-16 17:47:061101browse

一个全局的变量var JsonData;
我这里有一个Ajax处理的方法:
JScript code:

复制代码 代码如下:

function GetJson(DataSourceName) {
$.ajax({
type: “post”,
url: “Ajax/AjaxData.ashx?MethodName=” + DataSourceName,
contentType: “application/json;”,
data: “”,
dataType: “json”,
success: function (Result) {
JsonData = Result;
},
error: function (result) {
alert(“获取信息列表错误”);
window.close();
}
});
return JsonData;
}

然后我有一个类。
JScript code:
复制代码 代码如下:

function DrawDropDownList(sFieldRuleMethod)
{
GetJson(sFieldSourceName);
var b = JsonData;
}

如此,我在执行DrawDropDownList的时候,为什么总是获取不到JsonData呢?
我打断点跟踪了下, 发现是等DrawDropDownList方法里面的所有都执行完以后才会进入GetJson方法,
请问有什么办法把GetJson里面获得的Result数据拿出来?
不要在
复制代码 代码如下:

success: function (Result) {
//Do Something
},

我就是想把获得的数据拿出来用, 因为GetJson是一个通用的方法,不想在里面执行单个的逻辑.
不能在回调中return,并且需要同步,就可以了!
另外一种放过是不建议同步的,需要给我的函数增加一个函数参数作为回调函数,将ajax的结果传递到该函数,如下代码细节:
复制代码 代码如下:

function GetJson(DataSourceName,callback) {
$.ajax({
type: “post”,
url: “Ajax/AjaxData.ashx?MethodName=” + DataSourceName,
contentType: “application/json;”,
data: “”,
dataType: “json”,
success: function (Result) {
JsonData = Result;
callback(JsonData)
},
error: function (result) {
alert(“获取信息列表错误”);
window.close();
}
});
//return JsonData;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn