我有以下代码,它将项添加到json字符串
function addOrder(req, orderId, orderSource, transactiondtm) {
alert(orderId);
req.Request.orderslist.push({ ordid: orderId,
ordsource: orderSource,
tranndtm: transactiondtm });
}
function getDisplayPts(){
var req = {
"Request": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"number": Num,
"orderslist": {
"ordid": [],
"ordsource": [],
"tranndtm": []
}
}
};
$('#msListingProducts ul.msRows li input').each(function(index) {
addOrder(req,$('#hfOrderId'+index).val(),$('#hfOrderSource'+index).val(),$('#hfOrdTranDate'+index).val());
});
var str = JSON.stringify(req);
alert(str);
}
我得到的req.Request.orderslist.push()
不是一个函数..任何建议..对于某些行,orderId因未定义而来,是因为那个?
修改 我需要的json格式是,
{
"Request": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"memNum": "70000211981",
"orderslist": [
{
"ordid": "511",
"ordsource": "ONLINE",
"transactiondttm": "2014-01-09"
},
{
"ordid": "512",
"ordersource": "STORE",
"tranndttm": "2014-01-09"
}
]
}
}
答案 0 :(得分:2)
您正在尝试将对象元素作为数组访问,因此它会发出错误。准备对象req时,它应该是这样的
var req = {
"Request": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"number": Num,
"orderslist": []
}
};
现在,您可以使用推送方法。
答案 1 :(得分:1)
orderslist
在您的上下文中是object
,您不能push
任何内容。但是你可以将值推到下面,
req.Request.orderslist.ordid.push(orderId)
req.Request.orderslist.ordsource.push(orderSource)
req.Request.orderslist.tranndtm.push(transactiondtm)
答案 2 :(得分:1)
.push()
适用于array
,而orderslist
适用于object
。因此它不起作用。
但是ordid, ordsource, tranndtm
是数组。所以
req.Request.orderslist.ordid.push(orderId)
req.Request.orderslist.ordsource.push(orderSource)
req.Request.orderslist.tranndtm.push(transactiondtm)