如何从$.getJSON调用中以print_r()方式打印关联数组

how to print the associative array in print_r() fashion from a $.getJSON call?

本文关键字:式打印 数组 关联 print getJSON 调用      更新时间:2023-09-26

简单的事情。

使用$.getJSON,并在jquery回调函数中捕获被调用的.php文件的结果作为响应。json编码的php数组是一个关联数组。

$.getJSON("file.php",function(response){
// print the associative response array in var_dump or print_r fasion
});

file.php包含:

<?php
$my_array=array();
//$my_array['random_index1']="random_value1";
//$my_array['random_index2']="random_value2";
//$my_array['random_index3']="random_value3";
// and so on

echo json_encode($my_array);

?>

$my_array具有随机键和值。

如何像php中的print_r方式一样打印整个"response"数组?

编辑1:我想将其打印在网页或警告框中。并不是说我只想查看javascript控制台中的值(chrome、FF或其他什么)。

EDIT2:如果我按照如下方式编写$.getJSON的主体:为什么它不起作用:

    for(var i in response){
    console.log("i="+i+" content="+response[i]);
}

我相信console.dir()就是您想要的:

https://developer.mozilla.org/en-US/docs/Web/API/Console.dir

唯一的缺点是它不允许标记输出的每个对象,而且它也是一种非标准的控制台方法。

如果您有Chrome或Firebug,则可以使用console.log(response)。在控制台中,您可以单击记录的对象以查看其属性。

使用类似Doug Crockford的JSON库将响应转换为文本,并使用console.log 进行日志记录

function(response) {
    console.log(JSON.stringify(response));
}
$.getJSON("file.php", function(data) {
    var items = [];
    $.each(data, function(key, val) {
        items.push('<li id="' + key + '">' + val + '</li>');
    });
    $('<ul/>', {
        'index': 'my-list',
        html: items.join('')
    }).appendTo('body');
});

使用这种结构,示例循环遍历请求的数据,构建一个无序列表,并将其附加到正文中。

如果你想要一种替代格式,你可以修改每个格式,例如:

 $.each(data, function(key, val) {
       alert('key:' + key + ' value:' + val);
    });

我承认我借用了:http://api.jquery.com/jQuery.getJSON/