weixin_33696106
weixin_33696106
2014-04-03 04:16
采纳率: 0%
浏览 21

AJAX jQuery 400错误

I would like to get a second set of eye on this code.

formPaymentData is an JSON string of objects extracted from the form. I then went on to form a partial list params from formPaymentData, called _newData. I used _newData for my AJAX request.

the csrfmiddlewaretoken is a Django specific term, and I had to include it for the AJAX request. Without it, it produced a 403 error.

All I got was 400 error so I have no clue where to debug...

formPaymentData = $form.serializeArray();

console.log('before: -------------------------')
for (var i = 0; i < formPaymentData.length; i++) {
    console.log(formPaymentData[i].name + ': ' + formPaymentData[i].value);
}

var tempArray = [];
for (var i = 0; i < formPaymentData.length; i++) {
    if (formPaymentData[i].name == 'products' && formPaymentData[i].value != '') {
        tempArray.push(formPaymentData[i].value);
    }
}
productDataString = tempArray.join(',');
/*Construct JSON OBJECT */

reqParams = ['csrfmiddlewaretoken', 'order_number', 'shop_id'];
var _newData = []; // Extracted data
$.each(formPaymentData, function (index, data) {
    if ($.inArray(data.name, reqParams) !== -1 && data.name != 'products') {
        _newData.push(data);
    }
});

var dataProducts = {};
dataProducts.name = 'products';
dataProducts.value = productDataString;
_newData.push(dataProducts);

reqParams = ['height', 'width', 'length'];
$.each(formPaymentData, function (index, data) {
    if ($.inArray(data.name, reqParams) !== -1 && data.name != 'products') {
        _newData.push(data);
    }
});

JSON.stringify(_newData);
console.log('After stringify:');
console.log(_newData);
/*end Construct JSON OBJECT */

$.ajax({
    url: "/request_label",
    type: "POST",
    data: _newData,
    success: function (data) {
        console.log("Request complete.");
        console.log(data);
    },
    error: function (data) {
        console.log("failed");
        console.log(data);
    }
});

图片转代码服务由CSDN问答提供 功能建议

                    

我想再次关注这段代码。

formPaymentData 是从表单中提取的对象的JSON字符串。 然后,我从 formPaymentData 组成了一个局部列表参数,称为 _newData 。 我为AJAX请求使用了 _newData

csrfmiddlewaretoken是一个 Django 特定术语,我必须在AJAX请求中包括它。 没有它,它会产生 403 错误。

我只得到400错误,所以我不知道在哪里调试...

  formPaymentData = $ form.serializeArray();

 console.log('before:-------------------------')
 for(var i = 0; i  
     
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • weixin_33739627
    helloxielan 2014-04-03 05:31

    If your server is expecting JSON, you need to set contentType: 'application/json' in your $.ajax call; otherwise JQuery will send application/x-www-form-urlencoded which isn't what the server is expecting. Additionally, you need to call JSON.stringify on your data so jQuery will send it as is rather than trying to encode it as application/x-www-form-urlencoded

    点赞 评论

相关推荐