ajax向django后端服务发送跨域请求示例

 前端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 , 这三种类型的非简单请求仍然会成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值