如何从 json_encode php 获取一个值到 ajax

How to get one value from json_encode php to ajax

我试图从数组 json_encode 到 jquery 中一个一个地获取,但它总是出现错误 undefined 并且没有人工作,任何建议到我的代码

$response = array(
'antrian' => true,
'message' => 'Success print recipt'
);

echo json_encode($response);
$.ajax({
 url: urlPrintQueue,
 method: "POST",
 data: {id: id},
 dataType: 'json',
 success: function(result)  {
  console.log(result[0]); // antrian
  console.log(result[1]);  // message 
 }
});

对于 "antrian""message" 值我期望得到输出但我得到的是未定义

你是 运行 通过 json_encode() 的关联数组。

如果你将标准数值数组传递给json_encode(),你在JS中的result将是一个数组。但是,当您传递关联数组时,result 将成为一个对象。

而不是:

success: function(result)  {
  console.log(result[0]); // antrian
  console.log(result[1]);  // message 
}

您需要使用:

success: function(result)  {
  console.log(result.antrian); // antrian
  console.log(result.message);  // message 
}

这样做:

// Pase if not json ajax request
var json = JSON.parse(result);

// Like this
console.log(json.message + ' ' + json.antrin );

// Or loop
for (var i in json.list){
    console.log( json.list[i].message + ' ' + json.list[i].antrian );
}

此致