AJAX调用不适用于RESTful Web服务吗? [英] AJAX call doesnt work with RESTful web service?
问题描述
我有一个简单的Restful服务,它返回一个json.我想进行ajax调用以获取所需的数据.当我尝试使用Firefox的RestClient时,没有问题.服务返回json,我可以在其余客户端上看到json.但是,当我使用ajax调用时,它会失败.控制台显示200 OK
,但是错误函数在调用后执行.我进行了搜索,通常他们说这是跨域问题,但我无法解决.
I have a simple restful service that returns a json. I want to make an ajax call to get required data. When I try with firefox's RestClient there is no problem. Service returns the json and I can see the json on rest client. But when I use ajax call it fails. The console shows 200 OK
, but the error function executes after the call. I searched for this, commonly they say that its a cross domain problem but I fail to solve this.
这是错误功能{"readyState":0,"responseText":"","status":0,"statusText":"error"}
AJAX通话
$.ajax({
type:"GET",
url: "http://localhost:8080/myController/getInfo",
dataType:"json",
success: function(data){
alert(JSON.stringify(data));
},
error: function(msg){
alert("ERROR! \n" + JSON.stringify(msg));
}
});
Firefox的控制台消息
Firefox's console message
Content-Type application/json
Date Mon, 18 Feb 2013 11:51:41 GMT
Server Apache-Coyote/1.1
Transfer-Encoding chunked
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Host localhost:8080
Origin null
User-Agent Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
通话返回的数据:
{ "date": "1 hour ago", "photoUrl": "img/movie_detail/celal.jpg", "rating": "three", "title": "Celal ile Ceren" }
推荐答案
您似乎违反了 same origin policy restriction
,可防止您发送跨域AJAX调用.您已将http://localhost:8080/myController/getInfo
用作url,但这仅在从http://localhost:8080/
提供了包含此javascript的HTML页面时才有效.否则,浏览器将不允许您执行此AJAX调用.
It looks like you are violating the same origin policy restriction
which prevents you from sending cross domain AJAX calls. You have used http://localhost:8080/myController/getInfo
as url but this will only work if the HTML page containing this javascript was served from http://localhost:8080/
. Otherwise the browser won't allow you to perform this AJAX call.
作为一种可能的解决方法,您可以修改REST服务,使其在以下版本中支持 JSONP
除了JSON.然后,您将能够向它发送GET请求(POST不适用于jQuery的JSONP实现,因为它使用的是<script>
标记).
As a possible workaround you could modify your REST service so that it supports JSONP
in addition to JSON. Then you will be able to send GET requests to it (POST doesn't work with jQuery's JSONP implementation because it is using a <script>
tag).
这篇关于AJAX调用不适用于RESTful Web服务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!