Django AJAX POST请求中的JSON数据解析

时间:2018-02-12 13:16:24

标签: python jquery json ajax django

每当我通过Django中的AJAX post请求发送JSON对象时,我都会收到以下错误。

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

html中的代码:

 $("#submit").click(function(){

           var finalData{};
           finalData.name = $('#name').val();
           finalData.email = $('#email').val();
           finalData.password = $('#password').val();
           finalData.website = $('#website').val();

           $.ajax({

                  url: window.location.pathname,
                  type: "POST",
                  data :finalData,
                  success: function(){

                  },
                  error: function(){

                  }
                });

            });
    });



    <form  method = "POST" >
        {% csrf_token %}

        <div class="form-group">
          <label for="name">Name:</label>
          <input type="text" class="form-control" id="name" placeholder="Enter name" name="name" required>
        </div>

        <div class="form-group">
          <label for="email">Email:</label>
          <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" >
        </div>

        <div class="form-group">
          <label for="pwd">Password:</label>
          <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" >
        </div>

        <div class="form-group">
          <label for="name">Website:</label>
          <input type="text" class="form-control" id="website" placeholder="Enter website" name="website">
        </div>

        <div class="checkbox">
          <label><input type="checkbox" name="remember"> Remember me</label>
        </div>

        <button type="submit" id="submit" class="btn btn-default">Submit</button>
      </form>

Python中的代码:

def signup(request):

if request.method == 'POST':
    body = request.body
    response_json = body.decode('utf-8')
    x = json.loads(response_json)
    print(x)

    return render(request, 'signup.html', {})

else:
    return render(request, 'signup.html', {})

我可以使用Python中的以下命令打印响应

print(request.body)

示例JSON数据对象:

{
   name: test,
   email: test@gmail.com,
   password: test,
   website: www.test.com
}

我到底错过了什么?

1 个答案:

答案 0 :(得分:1)

其他人发布了答案并将其删除。它实际上对我有用。

以下是代码:

if request.method == 'POST':
   response_json = request.POST
   response_json = json.dumps(response_json)
   data = json.loads(response_json)
   print(data)