我正在尝试使用PHP从JS浏览器控制台打印我的JSON响应。 我在这里和其他网站上看过很多帖子,但我不能这样做。
我有像这样的JSON
{"0":{"codigo_intervencao":"Apoio Emocional - 5270"},"1":{"tempo":"30"},"2":{"codigo_intervencao":"Apoio Emocional - 5270"},"3":{"tempo":"30"},"4":{"codigo_intervencao":"Apoio Emocional - 5270"},"5":{"tempo":"231518"},"6":{"codigo_intervencao":"Apoio Emocional - 5270"}}
我想在控制台中打印,例如,键“codigo_intervencao”的每个值,但我无法实现。
我尝试过这样的事情:
$(document).ready(function() {
$( "#target" ).click(function() {
console.log("Select JS");
$.ajax({
type: "POST",
url: "select.php",
dataType: 'html',
success: function(response) {
console.log("Response:" + response); // Here it prints above json
var array = $.parseJSON(response);
var tempo = 0;
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
console.log(array[i]['codigo_intervencao']);
}
});
});
});
答案 0 :(得分:1)
您有一个JSON对象而不是数组。
var elements = $.parseJSON(response)
for (element in elements){
console.log(elements[element]['codigo_intervencao'])
}
迭代JSON并获取所需的元素。
答案 1 :(得分:0)
您提供的JSON示例将解析为Object。你可以尝试类似的东西:
const data = JSON.parse(response);
const array = Object.keys(data).map(key => data[key]);
array.forEach(item => console.log(item.codigo_intervencao))
对于没有codigo_intervencao
键的对象,您将未定义。或者,您可以使用for..in。