我似乎找不到这段代码有什么问题。我一直得到Uncaught SyntaxError:意外字符串在Chrome控制台。
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+'"}}';
请这样做:
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 });