A global variable var JsonData;
I have an Ajax processing method here:
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("Error getting information list");
window.close();
}
});
return JsonData;
}
Then I have a class.
JScript code:
function DrawDropDownList(sFieldRuleMethod)
{
GetJson(sFieldSourceName);
var b = JsonData;
}
So, why can’t I always get JsonData when I execute DrawDropDownList?
I tracked the interruption points and found that the GetJson method will be entered after everything in the DrawDropDownList method has been executed.
Is there any way to get the Result data obtained in GetJson?
Do not copy code in
success: function (Result) {
//Do Something
},
I just want to use the obtained data, because GetJson is a general method and I don’t want to execute a single logic in it.
Cannot return in callback, and needs to be synchronized, that’s it!
Another way of letting go is not recommended for synchronization. I need to add a function parameter to my function as a callback function and pass the ajax result to the function. The following code details:
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("Error getting information list") ;
window.close();
}
});
//return JsonData;
}