JS / AJAX - 从json显示正确的消息

时间:2018-03-20 11:25:33

标签: javascript ajax

var response = transport.responseJSON || transport.responseText.evalJSON(true) || {};

// console.log(response)
// log results
account: []
agreements: []
billing: []
order: {error: 1, message: "Ingenico ePayments Payment failed", goto_section: "payment"}
payment: []
shipping: []


alert(response.account.message);

根据响应中返回的消息,有一种方法可以循环访问AJAX响应并显示相关消息,而不是像上面那样硬编码值(response.account.message),例如错误将来自不同的部分,如:

account: {error: 1, message: "An account already exists for this email address."}

2 个答案:

答案 0 :(得分:1)

您可以结合使用Object.valuesArray.reduce

来执行此操作
Object.values(response).reduce((acc, val) => {
  if (typeof val === 'Object' && typeof val.message !== 'undefined') {
    return val
  } else {
    return acc
  }
})

或者如果你想要一个包含所有消息的数组:

Object.values(response)
  .filter(val => typeof val === 'Object')
  .filter(val => val.error === 1)
  .filter(val => typeof val.message !== 'undefined')
  .map(val => val.message);

请参阅ObjectArray文档

答案 1 :(得分:1)

您可能想要使用for..in循环,该循环遍历对象或其他iteratable的键。 More about for..in

var response = JSON.parse('{"account":{"error":1,"message":"your message"},"agreements":{"error":1,"message":"your second message"}}');

for (let type in response) {
  if (response[type].error) {
    var msg = response[type].message;

    console.log(type + " : '" + msg + "'");
  }
}