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

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);
    }
});
  • 写回答

1条回答 默认 最新

  • 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

    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配