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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改