jQuery JSONP不调用回调 [英] jQuery JSONP not calling the callback

查看:76
本文介绍了jQuery JSONP不调用回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jsonp和jquery上遇到问题.

I am having some problem with jsonp and jquery.

这是我的代码-

var myCallback = function(data) {
  console.log(data);
};

$.ajax({
  url: my_url,
  type: 'GET',
  dataType: 'jsonp',
  jsonp: 'callback',
  jsonpCallback: 'myCallback'
});

jQuery在my_url中添加了类似?callback=myCallback&_=1340513330866的内容,并且从my_url返回的数据为myCallback('abcd')-尽管实际上它将返回一些HTML代码而不是abcd.

jQuery adds something like ?callback=myCallback&_=1340513330866 to my_url and the data returned from my_url is myCallback('abcd') - although in reality it will be returning some HTML code instead of the abcd.

问题:abcd没有通过myCallback登录到控制台.那我在做什么错呢?我的印象是返回的数据将像在脚本标记中一样被执行?

Problem: abcd is not logged in console through myCallback. So what am i doing wrong ? I was under the impression that the data returned will be executed as it is inside script tags ?

推荐答案

如果使用自己的函数,则必须将其显式声明为 global .例如:

If you use your own function, then you have to explicitly declare it as global. For example:

window.myCallback = function(data) {
  console.log(data);
};

演示

说明

为响应成功的JSONP请求而应调用的每个函数必须是全局的. jQuery也正在这样做.这是因为JSONP就是包含一个带有<script>标记的(动态生成的(大部分时间))JavaScript文件,该文件仅包含一个函数调用.由于每个脚本都是在全局范围内评估的,因此调用的函数也必须是全局的.

Every function that should be called in response to a successful JSONP request must be global. jQuery is doing this as well. This is because JSONP is nothing else than including a (dynamically generated (most of the time)) JavaScript file with a <script> tag, which only contains a function call. Since each script is evaluated in global scope, the function that is called must be global as well.

这篇关于jQuery JSONP不调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆