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

Jon*_*ins 8 javascript ajax jquery jsonp cross-domain

服务器不会接受请求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);
    },
});
Run Code Online (Sandbox Code Playgroud)

JSONP文件:

jsonCallback({"test": "hello"});
Run Code Online (Sandbox Code Playgroud)

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

http://cross-domain.com/the_jsonp_file?callback=jsonCallback
Run Code Online (Sandbox Code Playgroud)

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

http://cross-domain.com/the_jsonp_file
Run Code Online (Sandbox Code Playgroud)

编辑:

这是我的整个情况:

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);
        };
    };
};
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

Uncaught TypeError: Property 'jsonCallback' of object [object Window] is not a function
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*dam 10

检查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 <script> tag, this option does nothing for jsonp | KevinB
    cache: 'true',
    dataType : 'jsonp'
});
Run Code Online (Sandbox Code Playgroud)

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

  • 那是因为你还没有定义一个名为jsonCallback的函数.jsonpCallback属性的值需要是在返回响应时要执行的全局可用函数. (2认同)