AJAX解决跨域的几种方式

 

在ajax发送请求时,在data中带着csrf_token,不过这需要在body中提前生成token值。

前端页面示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<button id="submit">提交</button>
{% csrf_token %}  <!-- 就这一行,csrf_token,也可以写在form表单中 -->
</body>
<!-- 首先引入 jQuery -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
    $('#submit').click(function () {
        $.ajax({
            url: "/test/",
            type: "POST",
            data: {"key": "value", "csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()},
            success: function (data) {
                console.log(data)
            }
        })
    })
</script>
</html>

views.py中代码示例:

from django.shortcuts import render, redirect, HttpResponse
def test(request):
    if request.method == "POST":
        print(request.POST)   # <QueryDict: {'key': ['value'], 'csrfmiddlewaretoken': ['i1pSO6cBt8kMeopZ684smHQZmLC6Zg1vLl8IDq2eEk3QEo9pvtjZNIjXRNaIimTo']}>
        return HttpResponse('OK啦')
    return render(request, 'test.html')

可以看到,token值在request.POST中。这种方式用的较多。

方式2

 

这种方式用的也比较多,我们使用jQuery.ajaxSetup()函数帮我们处理。该函数用于为ajax预先设置(更改)一些默认设置。记住,它是全局生效的。如果我们在这个函数中配置关于ajax的一些设置,那么在以后的ajax请求中,都会使用该函数配置的设置。比如,我们可以在这个函数中配置解决跨域的参数。

前端页面示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<button id="submit">提交</button>
</body>
<!-- 首先引入 jQuery -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

<script>
	// 预先设置ajax的某些配置,这里配置跨域参数
    $.ajaxSetup({
            data: {csrfmiddlewaretoken:'{{ csrf_token }}'}
        });
    // 后续的ajax请求,正常使用即可,无需关心跨域问题
    $('#submit').click(function () {
        $.ajax({
            url: "/test/",
            type: "POST",
            data: {"key": "value"},
            success: function (data) {
                console.log(data)
            }
        })
    })
</script>
</html>

views.py中代码示例:

def test(request):
    if request.method == "POST":
        print(request.POST)   # <QueryDict: {'csrfmiddlewaretoken': ['Ih344tfX2KyrOWZh1XbPfi5kS9NhJF0bbBMUTN5AdWhveWJHqiqmGjyinblT2LS4'], 'key': ['value']}>
        return HttpResponse('OK啦')
    return render(request, 'test.html')

可以看到,与方式1一样,token值都放在了request.POST中。

方式3

 

最后,还有一种放在request.META中,但是这种方式需要jquery.cookie.js文件搭配。

前端页面示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>

</head>
<body>
<button id="submit">提交</button>
</body>
<!-- 首先引入 jQuery -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<!-- 这种方式必须引入 jquery.cookie.js 文件,这里使用cdn,也可以下载到本地使用 -->
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

<script>
    $('#submit').click(function () {
        $.ajax({
            url: "/test/",
            type: "POST",
            headers: {"X-CSRFToken": $.cookie('csrftoken'), "zhangkai": 666},
            data: {"key": "value"},
            success: function (data) {
                console.log(data)
            }
        })
    })
</script>
</html>

views.py中代码示例:

from django.shortcuts import render, redirect, HttpResponse
def test(request):
    if request.method == "POST":
        print(request.POST)   # <QueryDict: {'key': ['value']}>
        print(request.META)   # 'HTTP_X_CSRFTOKEN': 'M1fqH9w6OIxkfKECCMYXe4Qb2tYPd1fCflYgwtmJZUgoFKo217duF5j9xvwrw77v'
        return HttpResponse('OK啦')
    return render(request, 'test.html')
posted @ 2020-03-26 17:09  干it的小张  阅读(1737)  评论(0编辑  收藏  举报