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

标签 javascript jquery ajax cross-domain 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 <script> tag, this option does nothing for jsonp | KevinB
    cache: 'true',
    dataType : 'jsonp'
});

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

关于javascript - 我可以在不在 URL 中添加 '?callback=' 参数的情况下发出 jQuery JSONP 请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12864096/

相关文章:

java - 每次 servlet 发生变化时如何执行 ajax 函数?

javascript - 西类牙语字体无法正确显示

javascript - 提交表单后按钮颜色保持不变

jquery - 使用JQuery解析XML,需要通过属性名查找

javascript - 关于jquery ajax,php文件已运行但成功功能不起作用

javascript - WebKit 请求未创建文件

javascript - 从复选框选择更改 AJAX jQuery url

javascript - Twitter Bootstrap 不可折叠的导航栏

javascript - 如何在不使用 Xcode 的情况下在 React Native 中添加自定义字体?

Jquery 选择具有相同 id 的容器 - IE 7 问题