我正在尝试将我的代码转换为Mootools (我更喜欢编码范例)。
我正在做跨域AJAX,其中我拥有这两个域(封闭网络)。我只是从我的服务器请求简单的JSON。我在Mootools (jQuery Works)中看到以下错误:
Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :
var url =
http://localhost:3000/
服务器:
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();
我已经尝试添加这些头文件,但都没有用:
'Accept': 'application/json',
'Content-Type': 'application/json'
这似乎是客户端的事情,而不是服务器端的事情,因为它在jQuery中工作。
发布于 2011-04-12 06:18:09
URL是什么样子的?jQuery通过在url中添加?callback=
或?foo=
来判断这是一个JSONP请求。Request.JSONP
改为使用选项callbackKey
。
JSONP (在任何库中)都没有method
选项,因为它只是注入了一个脚本标记。
var myRequest = new Request.JSONP({
url: url,
callbackKey: 'callback'
onComplete: function(data){}
}).send();
但是,我有一种感觉,您使用的不是JSONP,而是带有JSON的XHR。如果是这种情况,请使用Request.JSON
,而不是Request.JSONP
。
编辑
从这个答案的注释中可以看出,您没有使用JSONP,所以只需执行以下操作:
new Request.JSON({
url: url,
method: 'get',
onSuccess: function (data){
console.log(data)
}
}).send()
编辑2
要更改请求头,只需将它们添加为一个选项:
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()
发布于 2011-04-12 06:01:54
您的代码中存在语法错误。
var myRequest = new Request.JSONP({
url: url,
method: 'get',
onComplete: function(data){}
});
myRequest.send();
同样,响应应该用回调函数包装,例如:http://jsfiddle.net/zalun/yVbYQ/
发布于 2015-04-20 05:40:47
您的ajax调用应该如下所示
$.ajax({
type: "GET",
url: "http://localhost:17370/SampleService.asmx/HelloWorld",
data: "{}",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
async:false,
success:function(data,status){
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured!" + " | " +
XMLHttpRequest + " | " + textStatus + " | " +
errorThrown);
}
});
你的服务器端方法不应该返回简单的字符串,它应该返回jsonp格式的响应,你需要关注这个博客:
https://stackoverflow.com/questions/5629137
复制