简体   繁体   English

来自PHP的JSON对象值

[英]JSON object value from PHP

I am using JSON in PHP, and now I need to access it from JavaScript. 我在PHP中使用JSON,现在我需要从JavaScript访问它。 How do I pass a JSON object to JavaScript? 如何将JSON对象传递给JavaScript?

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

where My.js has: My.js在哪里:

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

How can I do it? 我该怎么做?

Assuming that you're using Ajax as your method to download the JSON, you would echo the result of the json_encode: 假设您使用Ajax作为下载JSON的方法,您将回显json_encode的结果:

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

    echo json_encode($array);
?>

And then within your call back event, you'd eval the response: 然后在你的回调事件中,你会评估回复:

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

Assuming that you have an XMLHttpRequest object with the name req . 假设您有一个名为reqXMLHttpRequest对象。

<?php
$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
$json = json_encode($array);
?>
<script type="text/javascript">
var myjson = <?php echo $json; ?>;
</script>

You could request the JSON data with AJAX or you could pass the data from PHP to JavaScript as a JavaScript variable: 您可以使用AJAX请求JSON数据,或者您可以将数据从PHP传递到JavaScript作为JavaScript变量:

$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
$json = json_encode($array);

echo '<script type="text/javascript">';
echo 'var myJson = "' . $json . '";';
echo '</script>';

edit: you have to eval the json string, otherwise you will just have a string not a object... 编辑:你必须评估json字符串,否则你将只有一个字符串而不是一个对象...

Off course keeping in mind all the guidelines about mixing PHP/HTML/JavaScript... 当然要记住有关混合PHP / HTML / JavaScript的所有指导原则......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM