django和vue實(shí)現(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對(duì)應(yīng)的代碼
def register(request):
if request.method=="POST":
if request.POST.get('name'):
return render(request,'success.html')
else:
return HttpResponse("賬號(hào)不能為空“)
當(dāng)提交表單的時(shí)候,會(huì)出現(xiàn)
如果前端可以有django渲染,這個(gè)問題很好解決,只需要在要提交的表單中加入{% 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實(shí)現(xiàn)數(shù)據(jù)交互的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
NDArray 與 numpy.ndarray 互相轉(zhuǎn)換方式
這篇文章主要介紹了NDArray 與 numpy.ndarray 互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python網(wǎng)絡(luò)編程中urllib2模塊的用法總結(jié)
使用urllib2模塊進(jìn)行基于url的HTTP請(qǐng)求等操作大家也許都比較熟悉,這里我們?cè)偕钊雭砹私庖幌聈rllib2針對(duì)HTTP的異常處理相關(guān)功能,一起來看一下Python網(wǎng)絡(luò)編程中urllib2模塊的用法總結(jié):2016-07-07

