我可以在不在URL中添加’?callback =’参数的情况下创建jQuery JSONP请求吗?

服务器不会接受请求URL中的任何参数,因此我需要删除URL中的所有额外参数,当然我无法控制服务器。

jQuery的:

$.ajax({ type: 'GET', url: 'http://cross-domain.com/the_jsonp_file, jsonpCallback: 'jsonCallback', contentType: 'application/json', cache: 'true', dataType: 'jsonp', success: function(json) { console.log(json);     }, }); 

JSONP文件:

 jsonCallback({"test": "hello"}); 

当我发送Ajax请求时,URL如下所示:

 http://cross-domain.com/the_jsonp_file?callback=jsonCallback 

但我需要这个(没有参数):

 http://cross-domain.com/the_jsonp_file 

编辑:

这是我的整个情况:

 function MyClass(imgs) { // imgs is array of URLs this.imgs = imgs; this.submit = function() { // button click event triggers this method this._show(); }; this._show = function() { var _this = this; for (var i = 0; i < _this.imgs.length; i++) { (function($, j) { $.ajax({ type: 'GET', url: _this.imgs[j], jsonp : false, jsonpCallback: 'jsonCallback', cache: 'true', dataType:'jsonp', success: function(json) { console.log(_this.imgs[j]);    }, }); })(jQuery, i); }; }; }; 

我收到此错误消息:

 Uncaught TypeError: Property 'jsonCallback' of object [object Window] is not a function 

奇怪的是很少有请求成功调用jsonCallback。

检查jQuery文档 – 他们说在ajax args中说jsonp:false和jsonpCallback:’callbackFunction’….

 $.ajax({ url: 'http://cross-domain.com/the_jsonp_file', jsonp : false, jsonpCallback: 'jsonCallback', // contentType: 'application/json', -- you can't set content type for a  

http://api.jquery.com/jQuery.ajax/

每个请求调用相同的回调jsonCallback ,所以我认为这是问题所在。

首先,文档中的Javascript:

  

客户端将JSONP文件(只是另一个Javascript文件)上传到服务器,如下所示:

 jsonCallback_27b2afa5c77c2510({"test": "hello"}); 

jsonCallback_之后添加随机hex字符串以分隔每个请求,如jQuery的默认回调。

从输入中读取随机hex字符串并设置为jsonpCallback

 function Gallery(imgs) { // imgs is array of URLs this.imgs = imgs; this.submit = function() { // button click event triggers this method this._show(); }; this._show = function() { var _this = this; for (var i = 0; i < _this.imgs.length; i++) { (function($, j) { $.ajax({ type: 'GET', url: _this.imgs[j][0], jsonp : false, jsonpCallback: 'jsonCallback_' + _this.imgs[j][1], cache: 'true', dataType:'jsonp', success: function(json) { // Process console.log(json.test); }, }); })(jQuery, i); }; }; }; 

谢谢@Adam @Kevin B @Dcullen和大家! :d

ps:我只输入上面的每个来源,例如,它可能不正确。

JSONP需要回调作为URL的一部分。 根据描述,我猜你正在访问的服务器不支持JSONP。

jQuery为您的文档添加了一个脚本标记,在添加时会运行API请求,响应会在您的代码中调用回调函数(这简化了它)。

如果您想要更准确的描述,可以查看维基百科。 http://en.wikipedia.org/wiki/JSONP#How_it_works