我对一个文件有一个简单的 ajax 查询,它基本上以 JSON 错误或成功返回。
即:
{"error":"1"}{"error_msg":" Invalid Expiry Date. Your credit card has not been billed for this transaction."}
然而问题是,即使我从 ajax 帖子中返回了这个 json 数据,我似乎根本无法访问这些数据。
我的 jquery 看起来像这样:
$.ajax({
type: 'POST',
url: 'process_sale.php',
data: $(this).serialize(),
cache: false,
dataType: 'json',
success: function(data) {
if(data['success']=='1'){
alert('hi');
$('#feedback').html('<strong>Congratulations</strong');
}
if(data['error']=='1') {
alert('hi');
$('#feedback').html(data['error_msg']);
}
// this following alert does nothing, because its empty even if the json
// returns what I pasted above example result.
alert(data['error'] + ' ' + data['success']);
}
});
所有警报都不会执行任何操作。
我在这里遗漏了一些非常明显的东西吗?我似乎无法理解为什么这不起作用,因为它似乎与我正在工作的其他代码完全相同。
最佳答案
您正在尝试解析无效的 JSON - 您的示例中有两个相邻的 JSON 对象。您需要将它们放在一个数组中,或者如果您希望 JS 理解它们,则将它们作为一个对象:
// You want this:
{"error":"1", // note , not {}
"error_msg":" Invalid Expiry Date. "+
"Your credit card has not been billed for this transaction."}
// or this (notice the `,` and the `[`, and `]`)
[{"error":"1"},{"error_msg":" Invalid Expiry Date. Your credit card has not been billed for this transaction."}]
根据您的其余代码,我敢打赌第一个代码会更好地满足您的需求。您可能更喜欢访问错误消息 data['error'] 而不是 data[0]['error']
关于jquery - 这个简单的 jquery/json 函数缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7212334/