I need to create a promise based on a ajax call to a web method. Originally, I had it working using this method:
$.ajax({
url: window.location.pathname + "/LoadPage"
)}.done(function(data){
//do some stuff
}).fail(function(){
//do other stuff
});
Then I ran into the issue of needing to wait for something to load, before doing something else, so I decided to create a variable to hold the promise object.
var promiseObj = $.ajax({...});
Then create a named function to call
function someFunction(data){...}
get access to the response from the server
var someData = promiseObj.responseText;
and call it like
promiseObj.done(someFunction(someData));
and it didn't work. I was getting undefined errors.
So I tried just to console.log
it
console.log(promiseObj) //shows the object
console.log(promiseObj.responseText) //gives undefined
What am I doing wrong? How to I send the data from the ajax call to another function using this method? Any help would be appreciated.
Firstly, simply remove the function wrapper in the .done
call - just call .done(someFunction)
. That will ensure that all of the parameters generated by the AJAX call are passed to someFunction
. It will also ensure that any this
context set in the $.ajax
call is passed correctly, too.
Having fixed that, the jqXHR
object should be found passed as the third parameter to someFunction
, so you can use that to access the .responseText
.
function someFunction(data, status, jqXHR) {
var text = jqXHR.responseText;
...
}
promiseObj.done(someFunction);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.