문제

I have the following logic within a function that needs to return a value based on the data returned back from an ajax call, however, I need the processing to happen after the success function.

var result;
console.log("First");
$.ajax ({
    dataType: "jsonp",
    url: url,
    async: false,
    success: function(data) {
        result = data;
        console.log("Result: " + result);
        console.log("Second");
    },
    error: function(err) {
        console.log(JSON.stringify(err))
    }
});
console.log("Third");

console.log("Data: " + result);

I expect to see the following in the console

First Result: [object Object] Second Third Data: [object Object]

However, I see the following in the console First Third Data: undefined Result: [object Object] Second

It would seem like it's actually performing asynchronously or rather asynchronously right when it needs to call the success function.

I have tried making this not asynchronous by adding async: false. Is there a way to have the follow code after the ajax call execute AFTER the success function has executed. I want to return a boolean depending on the data return to the function that is housing this ajax call.

Looking at the forums I can find similar situations but they don't ask my specific question about executing the code after the ajax call AND the success function.

도움이 되었습니까?

해결책

Data type jsonp does not support async:false

https://api.jquery.com/jQuery.ajax/ Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

Should be easy to work around that now that you know.

다른 팁

You need to use a function that you call at the end of your success callback. E.g. :

var result;
console.log("First");
$.ajax ({
    dataType: "jsonp",
    url: url,
    async: false,
    success: function(data) {
        result = data;
        console.log("Result: " + result);
        console.log("Second");
        afterSuccess();
    },
    error: function(err) {
        console.log(JSON.stringify(err))
    }
});

var afterSuccess = function() {
  console.log("Third");

  console.log("Data: " + result);
};

Note it would be cleaner to not use the higher-scope result variable, but instead to pass the result to afterSuccess as a parameter

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top