Jsonp
域1
index.html
<script> $(".get-service").click(function () { $.ajax({ url: "http://127.0.0.1:8005/service/", type: "get", dataType: "jsonp", jsonp: "callbacks", // 伪造ajax, 基于script // jsonpCallback: "alex", // 不写的话,默认是随机字符串 success: function (data) { console.log("//", data, typeof data); data = JSON.parse(data); console.log("//", data, typeof data); } }) }); </script>
域2
被请求的域
views.py
def service(request): # jsonp data = {"name": "sun", "age": 28} import json data = json.dumps(data) # 序列化 func = request.GET.get("callbacks") return HttpResponse("%s('%s')" % (func, data))
cors
原理:加***响应头(Access-Control-Allow-Origin)
域1
index.html
<script> $(".get-service").click(function () { $.ajax({ url: "http://127.0.0.1:8005/service/", data: {}, success: function (data) { console.log(data); data = JSON.parse(data); console.log(data); } }); }); </script>
域2
被请求的域
views.py
def service(request): # cors版本 data = {"name": "sun", "age": 28} import json data = json.dumps(data) # 序列化 response = HttpResponse(data) response["Access-Control-Allow-Origin"] = "http://127.0.0.1:8004" # 写*的话代码所有的ip地址都可以向本域跨域 return response