前端html文件,用的菜鸟教程给的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.ajax({url:"http://localhost:8008/",success:function(result){
$("#div1").html(result);
}});
});
</script>
</head>
<body>
<div id="div1"><h2>使用 jQuery AJAX 修改文本内容</h2></div>
<button>获取其他内容</button>
</body>
</html>
后端django视图代码:
完整代码:https://github.com/wangjinyu124419/django_ajax
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.http import HttpResponse
# Create your views here.
def index(request):
response = HttpResponse(json.dumps({"ajax": "cross"}))
#允许所有跨域请求
# response["Access-Control-Allow-Origin"] = "*"
# response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
# response["Access-Control-Max-Age"] = "1000"
# response["Access-Control-Allow-Headers"] = "*"
return response
默认不做跨域处理时,打开html文件控制台报如下的错误,就是不能跨域,应为两端前后端端口不一样,前端没法向后端发送ajax请求
修改一下django视图代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.http import HttpResponse
# Create your views here.
def index(request):
response = HttpResponse(json.dumps({"ajax": "cross"}))
#允许所有跨域请求
response["Access-Control-Allow-Origin"] = "*"
#指定某个端口的跨域请求
#response["Access-Control-Allow-Origin"] = "http://localhost:63345"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
其实加这一句就行:response["Access-Control-Allow-Origin"] = "*"
如图所示,ajax跨域请求发送成功,
“使用 jQuery AJAX 修改文本内容”已经被替换成了后端返回的{"ajax": "cross"}
为什么不设置Access-Control-Allow-Methods也能发送跨域请求?
https://stackoverflow.com/a/44385327/9917670
http://www.ruanyifeng.com/blog/2016/04/cors.html
JavanLu 说:
"If request method is not a case-sensitive match for any method in methods and is not a simple method, apply the cache and network error steps."
----参见 https://www.w3.org/TR/cors/#preflight-request
由于 GET | POST | HEAD 是简单方法,在通过预检请求后,即使 Access-Control-Allow-Methods 中没有返回 GET | POST | HEAD , 这三种类型的非简单请求仍然会成功。