I'm starting to use jQuery Deferred objects a bit more and I run into this issue:
I have a central AJAX function that performs pre validation of data, ajax set up and a few other things that sends to the server and returns xyz as data. How do I access 'xyz' in the 'then' part of a $.when(ajaxfn).then(dosomethingwithresult()); I get that ajaxfn returns a deferred object, but is there any way to pass the xhr's responseText forward?
I'm essentially doing it like this...
function ajaxfn开发者_如何学Python(data) {
prevalidate(data);
return $.ajax(settings);
}
$.when(ajaxfn).then(function() {
// put 'xyz' on the page somewhere.
});
At the moment I'm just passing in a $.data pointer to the ajaxfn, and then in the success of the ajax request, I have $('body',pos,result) and then access it like that from inside then $('body).data(pos) == xyz. I'd like to know if there's a better way of doing what I've described?
This can be simplified like so:
function ajaxfn(data) {
prevalidate(data);
return $.ajax(settings);
}
ajaxfn().then(function(response) {
console.debug(response);
});
There is no need to use a $.when
object. The ajax is already returning a promise.
Try this
$.when(ajaxfn()).then(function(data) {
// put 'xyz' on the page somewhere.
});
精彩评论