2009-08-27 100 views
2

我有以下功能伟大的工程,我用JSONP克服跨域,写了一个HTTP模块来改变内容类型,然后在URL没有附加一个回调名。如何从函数外部返回JSONP调用的结果?

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. 

}

的RE变量是alwayes来未定义。并且我不能在jsonp中使用async = false。 所以我怎样才能将结果返回到功能之外? ,我肯定需要做的是为subsequant电话。

请指教,谢谢。 问题是我不能在该函数外部返回的结果值

回答

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 
     } 
     .... 
    }); 
} 
+0

谢谢,看来这就像是唯一的出路,我要打电话内取得成功的功能,和连锁呼唤这样,但传递函数像你这样是更清洁。 – Adel 2009-08-27 18:29:52

0

声明该函数内部资源,使得它的范围局部的功能。所以有一个开始。在函数外面声明res,看看会发生什么。

0

添加异步:假Ajax请求对象

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

但不建议这样做,因为它会阻止浏览器,将视为不响应,直到Ajax调用完成。异步过程中应使用回拨功能像其他答案提