doujianzi8521 2011-08-29 10:41
浏览 101
已采纳

如何使用json_encode从php获取数据到javascript?

I am trying to map traceroutes to google maps.

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

I used json_encode($c, JSON_FORCE_OBJECT) and saved the file

Now, how do I access this using javascript, by directly equating it to new JS object?

earlier I used to have a data format like this on harddrive

var data12 = {

"route":[
{
    "ip": "some ip",

    "longitude": "some lng",

    "latitude": "some lat",

.....

and in my javascript it was used as

data=data12.route;

and then simply acces the members as data[1].latitude

  • 写回答

7条回答 默认 最新

  • dongliang2005 2011-08-29 10:49
    关注

    I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.

    For parsing JSON, simply do

    var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
    

    You can now access everything easily:

    alert ( obj.name );
    

    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.) 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.) 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥100 采用栈和深度优先算法对我的代码进行修改显示路径
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)
  • ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
  • ¥100 github贡献者给与奖励
  • ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00