【问题标题】:Problem sending data with ajax to django server使用 ajax 向 django 服务器发送数据时出现问题
【发布时间】:2021-04-04 09:49:55
【问题描述】:

我正在尝试将一些 ajax 数据发送到我的 Django 服务器,但遇到一个我难以调试的错误:
从 None 提高 JSONDecodeError("Expecting value", s, err.value) json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)。 这是我的脚本,也是我的 django 视图的一部分。

function UpdateUserResponse(productId, action, count) {
  $.ajax({
    url: "/updateitem/",
    method: "post",
    headers: {  'Content-Type':'application/json', "X-CSRFToken": csrftoken },
    dataType: "JSON",
     body: JSON.stringify({
      productId : productId,
      action: action,
      count: count
    }),
    success: response => {
      console.log("not relevant to this problem");
    }
  });
}

以及我如何尝试在我的视图中接收数据

def updateitem(request) :
    data =json.loads(request.body)
    productId=data['productId']
    action = data['action']
    count = data['count']

非常感谢您的帮助

【问题讨论】:

  • 我认为应该是 data 而不是键 body?即应该是data: JSON.stringify({...,而不是body: JSON.stringify({...。请参阅jQuery.ajax() 上的文档
  • 是的。就是这样......我有一些完美的“body”而不是数据的ajax,所以我没有找到正确的方向。非常感谢您的帮助阿卜杜勒阿齐兹

标签: jquery django ajax


【解决方案1】:

您的 ajax 请求格式无效。应该是这样的。

function UpdateUserResponse(productId, action, count) {
  $.ajax({
    url: "/updateitem/",
    method: "post",
    headers: {  'Content-Type':'application/json', "X-CSRFToken": csrftoken },
    dataType: "JSON",
    data: {
      'productId' : productId,
      'action': action,
      'count': count
    ),
    success: function(response) {
      console.log('Response', response);
      console.log("not relevant to this problem");
    },
    error : function(xhr, errMsg, err) {
    }
  });
}

在您看来,您可以按以下方式访问请求。

def updateitem(request) :
    if request.method == 'POST':
        productId = request.POST.get('productId')
        action = request.POST.get('action')
        count = request.POST.get('count')
        response_data = {}

        # Your update item to db code goes here 
        # Once update done return response
        response_data['result'] = 'Update item successful!'
        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:

您的控制台输出将是,

 Response, {result: "Update item successful!"}

【讨论】:

  • 注意到我会切换方法。我这样做的方式有什么问题?表现?非常感谢您花时间写这个答案 Zam Abdul
  • 现在 $.ajax 内容类型与意图不匹配
  • json.loads 和 request.POST 都可以安全使用。另一方面,request.post 和 request.get 支持第二个参数,它是一个默认值。示例:- productId = request.POST.get('productId', 100) 如果请求中不存在参数,则将使用值 100。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2011-09-17
  • 2021-07-30
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多