Return a value from an jQuery ajax function
I know there are a lot of questions regarding this but none of them seem to answer my particular question.
I'm having trouble constructing a function that includes an ajax call then returns a value. I am currently using:
hmis_query_temp_scalar: function(query_name) {
return $.ajax({
url: '/php_scripts/query_temp_scalar.php',
data: {query_name: query_name},
async: false
}).responseText
}
but I would like to make it asynchronous, but if I change it to async: true
It doesn't work, I just get undefined values. Is there any way of doing this?
The way I am currently using the function is as follows:
The page loads the following scripts:
$(document).ready(function() {
$.setQueryLink('active_clients', '1');
$.setQueryLink('active_clients_u18', '1');
$.setQueryLink('active_clients_19_59', '1');
$.setQueryLink('active_clients_o60', '1');
...
Which calls the following:
setQueryLink: function(query_name, type) {
var object = "#" + query_name;
var value = $.hmis_query_temp_scalar(query_name);
$(object).html(value);
$(object).attr('href', "/standard_queries.php?query=" + query_name + "&type=" + type);
}
Is there a better way of doing this? (I know it seems like it should be done in PHP but that's not what I want at the moment, I want the 开发者_开发问答asynchronous loading behavior of javascript) I don't see any but are there any reasons why I can't run this asynchronously?
What you want to do is split them up... Provide a success function for your request to call when it returns, and then take action based on the response.
i.e.
$.ajax({
type: 'POST',
url: 'formService.asmx/RemoveFieldOption',
contentType: 'application/json; charset=utf-8',
data: "{'fieldId':'1', 'optionId':'1'}",
dataType: 'json',
success: action_removeFieldOptionPass,
error: ajaxTestFail
});
function action_removeFieldOptionPass(result) {
$('#whatever').html(result);
}
精彩评论