jQuery.ajax成功回调未被调用,尽管Pyramid返回了响应
我有一个简单的 jQuery ajax 请求,想要发送到一个 Pyramid 的网页应用。
这是我的 Ajax 调用:
$.ajax({
type: 'POST',
url: 'http://localhost:6543/test',
dataType: 'json',
data: JSON.stringify({"username":"demo","email":"demo@something.com","Password":"1234"}),
success: function (response) {
alert(response);
},
error: function (msg) {
alert("error");
}
});
这是 Pyramid 的路由设置:
config.add_route('test', 'test')
config.add_view('tagzu.views.test', route_name='test', renderer='json')
这是 Pyramid 的视图设置:
def test(request):
return {'content':'Hello!'}
现在,当我调用这个服务时,我发送的是:
请求内容:
POST /test HTTP/1.1
Host: localhost:6543
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0) Gecko/20100101 Firefox/5.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 66
Origin: null
Pragma: no-cache
Cache-Control: no-cache
{"username":"demo","email":"demo@something.com","Password":"1234"}
然后我得到了这个响应:
HTTP/1.0 200 OK
Server: PasteWSGIServer/0.5 Python/2.7.1
Date: Fri, 08 Jul 2011 01:42:33 GMT
Content-Type: application/json; charset=UTF-8
Content-Length: 21
{"content": "Hello!"}
问题是:
我的 ajax 成功处理函数从来没有被调用过。只有错误处理函数一直在触发,并且显示错误信息 msg.statusText = 'error'
请告诉我,我是不是漏掉了什么。谢谢!
1 个回答
2
如果你也遇到和我一样的问题,比如说睡眠不足!!
为了上帝的缘故,确保你的html文件在同一个服务器上,因为这个问题是因为跨域调用造成的。用jQuery的html其实只是一个本地文件,而服务是运行在localhost上的。
所以服务器拒绝了这个请求,但没有给我任何错误信息,导致我不知道该往哪个方向找问题。
跨域问题是我最后才想到的,因为我太专注于Pyramid了,以为是它在搞什么鬼。真是搞笑,我浪费了那么多时间。