我似乎无法在此代码中找到错误的内容。 我一直在Chrome控制台中收到Uncaught SyntaxError:Unexpected string。
var json = '{"shipment":{"weight":"'+a[0].value+'","value":"0","quantity":"'+a[1].value+'","insurance":"false","dimensions":{"length":"30","width":"2","height":"10"},"origin":{"country":"'+a[2].value+'","formattedAddress":"'+a[3].value+'","locality":"'+a[4].value+'","postalCode":"'+a[5].value+'","contact":"'+a[6].value+'","email":"'+a[7].value+'","comments":"'+a[8].value+'"},"destination":{"country":"'+a[9].value+'","formattedAddress":"'+a[10].value+'","locality":"'+a[11].value'","postalCode":"'+a[12].value+'","contact":"'+a[13].value+'","email":"'+a[14].value+'","comments":"'+a[15].value+'"},"vehicleType":"'+a[16].value+'"}}';
答案 0 :(得分:3)
请为自己节省一千个头痛并改为:
var data = {
shipment: {
weight: a[0].value,
value: 0,
quantity: a[1].value,
insurance: "false",
dimensions: { length: "30", width: "2", height: "10" },
origin: {
country: a[2].value,
formattedAddress: a[3].value,
locality: a[4].value,
postalCode: a[5].value,
contact: a[6].value,
email: a[7].value,
comments: a[8].value
},
destination: {
country: a[9].value,
formattedAddress: a[10].value,
locality: a[11].value,
postalCode: a[12].value,
contact: a[13].value,
email: a[14].value,
comments: a[15].value
},
vehicleType: a[16].value
}
};
var json = JSON.stringify(data);
或者,如果您希望您的代码在未来可以维护一段时间:
function addressDataFromArray(arr) {
return {
country: a[0].value,
formattedAddress: a[1].value,
locality: a[2].value,
postalCode: a[3].value,
contact: a[4].value,
email: a[5].value,
comments: a[6].value
}
}
function shipmentDataFromArray(arr) {
var originData = addressDataFromArray( arr.slice(2, 8) ),
destinationData = addressDataFromArray( arr.slice(9, 15) );
return {
weight: arr[0].value,
value: 0,
quantity: arr[1].value,
insurance: "false",
dimensions: { length: "30", width: "2", height: "10" },
origin: originData,
destination: destinationData,
vehicleType: arr[16].value
}
}
var shipmentData = shipmentDataFromArray(a),
json = JSON.stringify({ shipment: shipmentData });