如何使用json_encode从php获取数据到javascript? [英] how to get data to javascript from php using json_encode?
问题描述
我试图将traceroutes映射到google地图。
I am trying to map traceroutes to google maps.
我在php中有一个数组,traceroute数据为
I have an array in php with traceroute data as
$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng
我使用 json_encode($ c,JSON_FORCE_OBJECT)
并保存了文件
现在,我如何使用javascript访问它,通过直接等同于新的JS对象?
Now, how do I access this using javascript, by directly equating it to new JS object?
这种硬盘上的数据格式
var data12 = {
"route":[
{
"ip": "some ip",
"longitude": "some lng",
"latitude": "some lat",
.....
data=data12.route;
,然后只是作为数据访问成员[1] .latitude
and then simply acces the members as data[1].latitude
推荐答案
我建议使用 jQuery库。缩小版本只有31 KB的大小,并提供了很多有用的功能。
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
对于解析JSON,只需执行
For parsing JSON, simply do
var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
您现在可以轻松存取:
alert ( obj.name );
注意:jQuery使用浏览器的原生JSON解析器使用 eval()
方法非常快速和安全。
Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval ()
method.
编辑 :要从服务器端到客户端获取数据,有两种可能:
Edit: To get data from the server side to the client side, there are two possibilities:
1)使用AJAX请求(用jQuery很简单):
1.) Use an AJAX request (quite simple with jQuery):
$.ajax ( {
url: "yourscript.php",
dataType: "json",
success: function ( data, textStatus, jqXHR ) {
// process the data, you only need the "data" argument
// jQuery will automatically parse the JSON for you!
}
} );
2。)在页面生成时将JSON对象写入Javascript源代码:
2.) Write the JSON object into the Javascript source code at page generation:
<?php
$json = json_encode ( $your_array, JSON_FORCE_OBJECT );
?>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
//]]>
</script>
这篇关于如何使用json_encode从php获取数据到javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!