错误:
最近在研究 django+extjs 的使用,我按照 ext 的例子,用js建了grid ,并取 django 服务器中的数据,但总是出现下面错误,取不到数据.
XMLHttpRequest cannot load http://127.0.0.1:8000/test/?_dc=1285778542180. Origin null is not allowed by Access-Control-Allow-Origin.
原因:
根据错误提示,google 了一下,找到了原因,因为我是直接打开本地 html 文件,然后在 html 文件里的js来取 django服务数据,这被似作是跨域访问了,当跨域 ajax 访问时,clinet 需要得到服务器的许可,方式是通过取得服务器送回的特殊 head 值来判断的,只要我们让服务端返回这几个头变量值就行了.
解决: (django 服务端修改一下)
res=HttpResponse()
res['Access-Control-Allow-Origin']='*'
res['Access-Control-Allow-Headers']='my-header,X-Requested-With'
res.write('{"rows":[{....},{....}......]}')
return res
参考 w3c 的文献:
http://www.w3.org/TR/2010/WD-cors-20100727/#introduction