如何从函数外部的JSONP调用返回结果?

时间:2009-08-27 15:25:57

标签: javascript jquery ajax json jsonp

我有以下功能,它运行得很好,我使用JSONP来克服跨域,写了一个http模块来改变内容类型,并没有在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.

}

res变量是alwayes未定义。而且我不能在jsonp中使用async = false。 那么如何才能将结果返回到函数外部? 我肯定需要为次要的电话做这件事。

请指教,谢谢。 问题是我无法在此函数之外返回结果值

3 个答案:

答案 0 :(得分:6)

You simply cannot do this.

你必须重写你的代码流,以便AddSecurityCode获取一个callback参数(即一个运行的函数),然后在你的成功回调中调用:

function AddSecurityCode(securityCode, token, callback) {

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

答案 1 :(得分:0)

你在函数内部声明了res,使其作为该函数的局部范围。所以有一个开始。在函数外部声明res,看看会发生什么。

答案 2 :(得分:0)

将async:false添加到ajax请求对象

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

但不建议这样做,因为它会阻止浏览器,并且在ajax调用完成之前会被视为无响应。异步进程应该使用回调函数,如提及的其他答案

相关问题