![](/img/trans.png)
[英]How to post an array of JSON objects to a Struts2 action using jQuery?
[英]How to post JSON array of objects using JQuery
我在Chrome瀏覽器控制台中使用Javascript / jQuery將數據發布到頁面上。 (我在Shopify管理員中執行此操作,因為它不具有批量導入運費的功能)。
這是我正在使用的代碼:
make_weight_based_shipping_rate(8267845, 98, 99, 'Test Shipping Rate', 59);
function make_weight_based_shipping_rate(cid, minWeight, maxWeight, name, price) {
$.post('/admin/weight_based_shipping_rates.json', {
weight_based_shipping_rate: {
country_id: cid,
name: name,
offsets: [{disabled:true, offset:0, province_id:145570341}, {disabled:true, offset:0, province_id:145570345}],
weight_high: maxWeight,
weight_low: minWeight,
price: price
}
});
}
效果很好,除了我的請求中包含對象數組的一行-以“ offsets”開頭的行。
如果我在此行上只有一個JSON對象,而不是數組(通過不包括方括號),則此代碼有效。 但是,作為數組,Shopify返回錯誤“ 422(不可處理的實體)”,並且在響應的正文中顯示“ {{errors”:{“ shipping_rate_offsets”:[“ is invalid”]}}}'。
我是否正確格式化了此JSON對象? 如果不是,是否還有其他方法可以實現此目的,而不是使用JQuery Post方法?
我最終想通了。 默認情況下,JQuery POST和AJAX請求被編碼為“ application / x-www-form-urlencoded”。 這在大多數情況下都有效,但是當它獲得諸如“偏移”之類的數組時,它似乎會失敗。
為了解決這個問題,首先我必須對提交的數據使用JSON.stringify()函數。 然后在進行POST之前,我使用了ajaxSetup()函數將內容類型設置為“ application / json”。 我修改后的代碼現在是:
make_weight_based_shipping_rate(8267845, 98, 99, 'Test Shipping Rate', 59);
function make_weight_based_shipping_rate(cid, minWeight, maxWeight, name, price) {
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
$.post('/admin/weight_based_shipping_rates.json', JSON.stringify({
weight_based_shipping_rate: {
country_id: cid,
name: name,
offsets: [{disabled:true, offset:0, province_id:145570341}, {disabled:true, offset:0.00, province_id:145570345}],
weight_high: maxWeight,
weight_low: minWeight,
price: price
}
}));
}
我希望這對其他人有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.