我正在尝试将我的代码转换为 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/