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 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题