欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

django和vue實(shí)現(xiàn)數(shù)據(jù)交互的方法

 更新時(shí)間:2019年08月21日 08:59:50   作者:Qc1998  
今天小編就為大家分享一篇django和vue實(shí)現(xiàn)數(shù)據(jù)交互的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

我使用的是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ù)交互的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論