来自PHP的JSON对象值

ven*_*lam 2 javascript php ajax json

我在PHP中使用JSON,现在我需要从JavaScript访问它.如何将JSON对象传递给JavaScript?

<?php
    $array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
    $json = json_encode($array);
>
Run Code Online (Sandbox Code Playgroud)

My.js在哪里:

showAll(){
    alert("Show All Json Objects");
    // How do I get the JSON value here?
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Gav*_*vin 6

假设您使用Ajax作为下载JSON的方法,您将回显json_encode的结果:

<?php
    $array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");

    echo json_encode($array);
?>
Run Code Online (Sandbox Code Playgroud)

然后在你的回调事件中,你会评估回复:

var obj = eval('(' + req.ResponseText + ')');
for(var i in obj) {
    alert(i + ': ' + obj[i]);
}
Run Code Online (Sandbox Code Playgroud)

假设您有一个名称为XMLHttpRequest的对象req.