jquery function with variable problem
I'm trying to return a list of select options to a JqGrid Add feature. I have a javascript/jquery function that does a GET to get a string preformatted to work with JqGrid. I'm having trouble returning the results to the JqGrid though. How do I return the data from the jQuery Get function?
function getDealerPoolSelectOptions() {
var selectOptions = "1:A;";
$.get("DealerManagemen开发者_StackOverflowt/GetAllDealerPoolCodes", function(data) {
alert("Data: " + data.toString()); //Displays all the data I'm looking for
selectOptions = data;
});
alert("SelectOptions: " + selectOptions); //Just Displays the 1:A
return selectOptions;
}
$.get
begins an asynchronous AJAX request and calls your callback function(data) ...
once it is done. $.get
itself returns before the request is complete. The alert("SelectOptions ...")
part runs immediately (before the data is retrieved) so selectOptions
isn't set yet.
jQuery ajax, by default, makes an asynchronous request (meaning it will make the request in the background, without blocking execution in the rest of the function).
EDIT: While you can make synchronous requests, I should note that this is very discouraged. Instead, you should design your code in a way that takes advantage of event driven programming.
You can make a synchronous request like this:
function getDealerPoolSelectOptions() {
var selectOptions = "1:A;";
$.ajax({
async: false,
url: "DealerManagement/GetAllDealerPoolCodes",
success: function(data) {
alert("Data: " + data.toString()); //Displays all the data I'm looking for
selectOptions = data;
}
});
alert("SelectOptions: " + selectOptions);
return selectOptions;
}
Probably you should describe your original problem. What you want to do with jqGrid?
Do you want to fill select of edit or search field with the data from the server? You should use dataUrl
of the editoptions or the searchoptions. The feature (dataUrl
) are introduced exactly for loading the data per ajax.
If the data which you can provide from the server can be only JSON and not in the format which are waiting by jqGrid you can use buildSelect
additionally to reformat the data returned from the server. For more information see my old answer.
The alert gets called before the selectOptions = data;
because ajax functions are called asynchronously. If you want something to happen, like adding the data to a grid, call it in the get callback after you set the selectOptions data.
精彩评论