weixin_33739541 2018-03-22 22:27 采纳率: 0%
浏览 75

Django Ajax发布空数据

I'm trying to post data to a django view using ajax. I have no errors just there is no data returned. Here is my javascript ajax:

 function PostGoal(){
    console.log('POSTGOAL!!!')
    data_s = {
            'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
            'goal': { 'name':'gg','box':'sasa' }
        }

    $.ajax({
        method: "POST",
        url: "http://127.0.0.1:8000/",//"{% url 'home' %}",//"/",//"{% url 'home' %}",
        contentType: 'application/json',
        //data: JSON.stringify(data_s),
        data: {'QQww': "1"},
        //dataType: 'json',//expected type of response
        success: function (data) {
          console.log('aa'+JSON.stringify(data))
        },
        error: function(xhr,errmsg,err){
            console.log('err: '+JSON.stringify(err)+' msg:'+errmsg)
        }
    });
}

here is my view function:

def analyzer(request):
    if request.method == 'POST':
    post_data = request.POST
    print(post_data)
    print ('  ajax:',request.is_ajax())

The boolean request.is_ajax() is ajax is always False request.data or request.POST.data do not exist and same for GET: request.GET is empty. However I can see in the log in the terminal :

  [22/Mar/2018 22:15:26] "GET /?QQww=1 HTTP/1.1" 200 9746

so essentially the data are parsed in the url? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • weixin_33686714 2018-03-23 16:46
    关注

    I read in some other posts that 'method' was the right field to specify the call. For some reason, the parameter 'method' is NOT working and the correct field is 'type':

     $.ajaxSetup({
          headers: { "X-CSRFToken": '{{csrf_token}}' }
        });
     $.ajax({
        type: "POST",
        url: "http://127.0.0.1:8000/",//"{% url 'home' %}",//"/",//"{% url 'home' %}",
        contentType: 'application/json',
        //data: JSON.stringify(data_s),
        data: {'QQww': "1"},
        //dataType: 'json',//expected type of response
        success: function (data) {
          console.log('aa'+JSON.stringify(data))
        },
        error: function(xhr,errmsg,err){
            console.log('err: '+JSON.stringify(err)+' msg:'+errmsg)
        }
    });
    

    The html button also needs to be of type 'button' not 'submit':

    <button type="button" class="btn btn-primary btn-large" id="yesbtn" name="yesbtn" value="yesbtn" onclick="PostGoal();">Yes &raquo;</button> 
    

    I also added the ajax setup for the csrf token to correct the error:

      'Forbidden (CSRF token missing or incorrect.): /'
    

    I hope it helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号