How to return the result from JSONP call outside the function?

此生再无相见时 提交于 2019-12-22 18:49:07

问题


I have the following function which works great, i used JSONP to overcome cross-domain, wrote an http module to alter the content-type and didn't append a callback name in the url.

function AddSecurityCode(securityCode, token) {
var res=0;
$.ajax({ url: "http://localhost:4000/External.asmx/AddSecurityCode",
    data: { securityCode: JSON.stringify(securityCode),
        token: JSON.stringify(token)
    },
    dataType: "jsonp",
    success: function(json) {
        alert(json); //Alerts the result correctly
        res = json;
    },
    error: function() {
        alert("Hit error fn!");
    }
});
return res; //this is return before the success function? not sure.

}

the res variable is alwayes comes undefined. and i can't use async=false with jsonp. so how can i return the result to outside the function?? and i sure need to do that for subsequant calls.

Please advice, thanks. The problem is i can't return the result value outside this function


回答1:


You simply cannot do this.

You have to rewrite your code flow so that AddSecurityCode takes a callback parameter (i.e. a function to run) that you then invoke inside your success callback:

function AddSecurityCode(securityCode, token, callback) {

    $.ajax({
        ....
        success: function(json) {
            alert(json); //Alerts the result correctly
            callback(json); // HERE BE THE CHANGE
        }
        ....
    });
}



回答2:


You have res declared inside the function, making it's scope local to that function. So there's a start. Declare res outside the function and see what happens.




回答3:


Add async: false to the ajax request object

$.ajax({
   ...
   async: false,
   ...
});
return res;

But this is not recommended since it will block the browser and will seen as not responding until the ajax call completed. Async process should use callback function like the other answer mentioning



来源:https://stackoverflow.com/questions/1341810/how-to-return-the-result-from-jsonp-call-outside-the-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!