Skip to main content
 首页 » 编程设计

python之Django AJAX POST请求中JSON数据解析

2024年09月07日43arxive

每当我在 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 
} 

我到底错过了什么?

请您参考如下方法:

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

代码如下:

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