dqhr76378 2013-06-27 01:43
浏览 88
已采纳

将JSON从PHP传递给JavaScript变量

I'm making an aplication with phonegap and I'm stuck trying to send JSON data from the PHP on the server to JavaScript on the device. I want to do something like:

var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" +  '}';

the php works fine and returns somethig like:

"[{"id":"1","name":"Art for everyone","image":null,"name2":"June 29, 2013: 11:00am.","description":"With reservation
Free entrance","description2":null}]"

I want that result in a javascript variable to work later with:

var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2; 

What I want to do is something like:

var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" +  '}';
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2; 

How can I make the first line work? is it possible to make the first line work? PS. I do not have much experience with JSON arrays.



Ok I tried ajax and works, I used:

console.log("before"); 

var jqxhr = $.ajax( "http://www.hel.com/LoadDB.php?table=exhibitions" )
            .done(function(data) { console.log(data); })
            .fail(function() { console.log("error"); })
            .always(function() { console.log("complete"); });

console.log("after");

more info in:

api.jquery.com

  • 写回答

3条回答 默认 最新

  • dongyan1936 2013-06-27 02:34
    关注

    Try this:

    PHP: (json.php)

    <?php
        header("Content-Type: text/json");
    
        //the data format your question mentioned
        $data = array("Table"=>array(array("id"=>"1","name"=>"Art for everyone","image"=>null,"name2"=>"June 29, 2013","description"=>"With reservation
    Free entrance","description2"=>null)));
    
        echo json_encode($data);
    ?>
    

    Front-end:

    <!DOCTYPE html>
    <html>
    <head>
     <title></title>
    </head>
    <body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>
        $.get("json.php",function(json){
            alert(json.Table[0].name);
        });
    </script>
    </body>
    </html> 
    

    Hope this is helpful for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!