问个 ajax 的问题,谢谢帮助

2018-03-03 20:14:21 +08:00
 bmcjxhgwy
在 django 中,前端发送了数据,我后台返回了{‘ res ’:0},在前端 response 中也接受到了,为什么 ajax 一直走 err 啊?是返回格式不对吗,应该在哪改啊?谢谢了
3945 次点击
所在节点    Python
28 条回复
brickyang
2018-03-03 21:59:05 +08:00
另外针对跨域,个人倾向于优先选择 CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
leamtrop
2018-03-03 22:11:52 +08:00
dataType 属性值改成 JSON 试试
bmcjxhgwy
2018-03-03 22:16:09 +08:00
zhuzhuyule
2018-03-03 22:18:29 +08:00
$.ajax(
....
datatype: 'text',
success: console.log,
error: console.error
);

因为你后台返回的数据格式不一定处理正确了,所以这里用`datatype: 'text'`,如果可以行得通,
再使用:

$.ajax(
....
datatype: 'json',
success: console.log,
error: console.error
);

应该问题可以解决了。
bmcjxhgwy
2018-03-03 22:42:02 +08:00
@sublime 改了后现在服务器端报 500 错误...

def test(request):
if request.method == "GET":
name = request.GET.get("name")
print(name)
return HttpResponse("func({'res':0})")
else:
name = request.POST.get("name")
print(name)
return HttpResponse("func({'res':1})")


$.ajax({
url:'http://127.0.0.1:8000/laoguo/',
type:'get',
data:{'name':'laoguo'},
dataType:'jsonp',
success:function func(data){
if(data.res == 0){
alert('get')
}else{
alert('error')
}
},
error:function func(data){
alert(data.res)
}
})
sublime
2018-03-03 23:06:03 +08:00
@bmcjxhgwy 你直接搜索关键字 django jsonp
g8287694
2018-03-04 10:20:14 +08:00
我记得 jsonp 的返回值是有时间戳的吧?
zhwithsweet
2018-03-04 15:28:26 +08:00
jsonp 技术有点老了,建议 cors

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/434542

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX