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')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM