django和vue實現(xiàn)數(shù)據(jù)交互的方法
我使用的是jQuery的ajax與django進(jìn)行數(shù)據(jù)交互,遇到的問題是django的csrf
傳輸數(shù)據(jù)的方法如下:
$(function() {
$.ajax({
url: 'account/register',
type: 'post',
dataType:'json',
data: $('#form1').serialize(),
success: function (result) {
console.log(result);
if (result) {
alert("result");
}
},
error: function () {
alert("error");
},
})
})
})
django對應(yīng)的代碼
def register(request):
if request.method=="POST":
if request.POST.get('name'):
return render(request,'success.html')
else:
return HttpResponse("賬號不能為空“)
當(dāng)提交表單的時候,會出現(xiàn)
如果前端可以有django渲染,這個問題很好解決,只需要在要提交的表單中加入{% csrf_token %},但是在這中情況下顯然是行不通的,通過在網(wǎng)上的搜索,我找到了這樣的解決方案,完整代碼如下:
$(function() {
$('#sub').click(function () {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
url: 'account/register',
type: 'post',
dataType:'json',
data: $('#form1').serialize(),
success: function (result) {
console.log(result);
if (result) {
alert("result");
}
},
error: function () {
alert("success");
},
})
})
})
這樣就可以成功提交表單了
方法來源 https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
以上這篇django和vue實現(xiàn)數(shù)據(jù)交互的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python 將json數(shù)據(jù)提取轉(zhuǎn)化為txt的方法
今天小編就為大家分享一篇python 將json數(shù)據(jù)提取轉(zhuǎn)化為txt的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Pycharm使用遠(yuǎn)程linux服務(wù)器conda/python環(huán)境在本地運行的方法(圖解))
這篇文章主要介紹了Pycharm使用遠(yuǎn)程linux服務(wù)器conda/python環(huán)境在本地運行的方法,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
對網(wǎng)站內(nèi)嵌gradio應(yīng)用的輸入輸出做審核實現(xiàn)詳解
這篇文章主要為大家介紹了對網(wǎng)站內(nèi)嵌gradio應(yīng)用的輸入輸出做審核實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
python中plot實現(xiàn)即時數(shù)據(jù)動態(tài)顯示方法
這篇文章主要為大家詳細(xì)介紹了python中plot實現(xiàn)即時數(shù)據(jù)動態(tài)顯示方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06

