我正在尝试使用 JSONP 回调与服务器进行通信。
这是我的代码
$('.icwsDownloadRecording').click(function(){
var id = $(this).attr('data-recordingid');
$.ajax({
type: 'GET',
url: 'http://example.com/Default2.aspx',
data: {'ID': id},
dataType: 'jsonp',
cache: false,
timeout: 40000,
crossDomain:true,
jsonp: "MyCallbackFunction",
});
});
function MyCallbackFunction(data)
{
//process data further
console.log(data);
if(!data || data.url.length < 5){
return;
}
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload( data.url, {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
}
这里的问题是我不断在控制台中收到此消息
ReferenceError: MyCallbackFunction is not defined
我确实定义了这个,正如您在上面的代码中看到的那样
服务器响应如下所示
MyCallbackFunction("{'URL': 'http:\/\/example.com:8106\/ghjgj3835396265336634646562363030303122226D616C686179656B22535353557DBE0C305645E2DE110AA1D7F8792E96A3'}");
如何解决这个问题?
已编辑
这是我在昆汀回答后的代码,这是我的新代码
$(function(){
$('.icwsDownloadRecording').click(function(){
var id = $(this).attr('data-recordingid');
$.ajax({
type: 'GET',
url: 'http://example.com/Default2.aspx',
data: {'ID': id},
dataType: 'jsonp',
timeout: 40000,
success: function(data){
//process data further
console.log(data);
if(!data || data.url.length < 5){
return;
}
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload( data.url, {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
}
});
});
});
最佳答案
除非您将所有代码都包装在另一个函数中,否则应该可以工作。
不过,使用硬编码的函数名称是不好的做法。
更新:
$(function(){
您确实将所有代码包装在另一个函数中。
删除这个:
jsonp: "MyCallbackFunction",
替换为:
success: MyCallbackFunction
或者您可以在那里放置一个匿名函数表达式(正如您在编辑中所做的那样)
让 jQuery 生成一个唯一的函数名称(这可以保护您免受竞争条件的影响)并允许服务器使用回调
查询字符串参数来确定要使用的函数名称。
MyCallbackFunction
与 ajax 调用位于同一范围内,因此该函数可以使用它(可以将其复制到适当命名的全局)。
修复该问题后,您还会遇到一个问题:
MyCallbackFunction("{'URL':
您的响应是在 JavaScript 字符串中编码的 JSON,但您试图将其视为 JavaScript 对象。
或者:
- 修复服务器,使其不会对 JSON 进行字符串化或
- 通过 JSON.parse 运行第一个参数
crossDomain:true,
删除它。它在这里没有任何作用。 (它所做的只是,当使用 XHR(您没有使用)到同一源(您没有定位)时,抑制跨源请求通常不允许的自定义 header ,以便您可以执行到不同源的 HTTP 重定向)。
cache: false,
这是 JSONP 请求的默认值。包含它是没有意义的。
<小时/>return false; //this is critical to stop the click event which will trigger a normal file download!
如果要停止单击事件,则需要从单击事件处理函数(而不是 Ajax 成功处理函数)返回 false。
您不能等到 Ajax 函数运行并收到响应后再执行此操作。 Ajax is asynchronous 。
关于javascript - 如何使用JSONP回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190936/