我正在尝试从jquery到休息服务进行ajax调用.使用的其他服务正是来自mkyong博客的教程,这个:http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/
该服务有效,但是当我尝试从jQuery调用时,在Firebug中有200个状态代码,但在响应部分中没有任何内容.
这是带有ajax调用的html页面:
<html>
<head>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
<button id="ajax">ajax call</button>
<button id="json">json</button>
<script type="text/javascript">
$('#json').click(function(){
alert('json');
$.getJSON("http://localhost:8080/restws/json/product/get",
function(data) {
alert(data);
});
});
$('#ajax').click(function(){
alert('ajax');
$.ajax({
type: "GET",
dataType: "json",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我无法弄明白我哪里出错了,你能不能告诉我我做错了什么?
谢谢!
Roc*_*mat 78
您从与请求的主机不同的主机运行HTML.因此,您将受到相同原始策略的阻止.
解决这个问题的一种方法是使用JSONP.这允许跨站点请求.
在JSON中,您将被返回:
{a: 5, b: 6}
Run Code Online (Sandbox Code Playgroud)
在JSONP中,JSON包含在函数调用中,因此它变为脚本,而不是对象.
callback({a: 5, b: 6})
Run Code Online (Sandbox Code Playgroud)
您需要编辑REST服务以接受调用的参数callback,然后使用该参数的值作为函数名称.您还应该更改content-type为application/javascript.
例如:http://localhost:8080/restws/json/product/get?callback=process应输出:
process({a: 5, b: 6})
Run Code Online (Sandbox Code Playgroud)
在JavaScript中,您需要告诉jQuery使用JSONP.为此,您需要附加?callback=?到URL.
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
Run Code Online (Sandbox Code Playgroud)
如果您使用$.ajax,它将自动附加,?callback=?如果您告诉它使用jsonp.
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
Run Code Online (Sandbox Code Playgroud)