jquery - JSONP 在 jQuery 中有效,但在 mootools 中无效

标签 jquery mootools jsonp

我正在尝试将我的代码转换为 Mootools(我更喜欢这种编码范例)。

我正在做跨域 AJAX,我拥有两个域(封闭网络)。我只是从我的服务器请求简单的 JSON。我在 Mootools 中收到这些错误(jQuery 有效):

Resource interpreted as Script but transferred with MIME type text/plain. Uncaught SyntaxError: Unexpected token :

var url = <a href="http://localhost:3000/" rel="noreferrer noopener nofollow">http://localhost:3000/</a>

服务器:

var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});

jQuery:

$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});

Mootools:

var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();

我尝试添加这些 header 但无济于事。:

'Accept': 'application/json',
'Content-Type': 'application/json'

这似乎是客户端的事情,而不是服务器端的事情,因为它在 jQuery 中工作。

最佳答案

网址是什么样的? jQuery 通过在 url 中添加 ?callback=?foo= 来判断这是一个 JSONP 请求。 Request.JSONP 使用选项 callbackKey

JSONP(在任何库中)都没有 method 选项,因为它只是注入(inject)脚本标记。

var myRequest = new Request.JSONP({
  url: url,
  callbackKey: 'callback'
  onComplete: function(data){}
}).send();

但是,我有一种感觉,您没有使用 JSONP,而是使用 XHR 和 JSON。如果是这种情况,请使用 Request.JSON,而不是 Request.JSONP

<小时/>

编辑

从这个答案的评论来看,您没有使用 JSONP,所以只需执行以下操作:

new Request.JSON({
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()
<小时/>

编辑 2

要更改请求 header ,只需将它们添加为选项:

new Request.JSON({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  },
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()

关于jquery - JSONP 在 jQuery 中有效,但在 mootools 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629137/

相关文章:

javascript - 带有CSS转换的 slider 中的无限循环

javascript - jQuery 动态居中未按预期工作

javascript - 使用 $ajax 对象重新运行 ajax 调用?

javascript - 如何使用 Javascript 设置表单元素的值?

javascript - 具有淡入淡出效果的全背景图像

javascript - AJAX跨域调用

javascript - 如何让 Javascript 停止从展开/折叠栏中删除我的填充

forms - Mootools停止表单提交方法

javascript - 为什么这里是 "Unexpected token"错误?

asp.net - WCF 服务和 AspNetCompatibilityEnabled ="true"导致请求错误