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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同