使用php从JSON数组填充Web数据

时间:2014-07-15 17:47:13

标签: javascript php jquery json

我已经玩了几天JSON,我真的认为这是一种非常酷的方式来交换使用它的数据...我正在使用jquery mobile构建一个应用程序,我试图填充Json数据,到目前为止,我尝试过这种方法:

从名为movie-details.json的json文件中我得到了:

{"movies":[{"id":"1","name":"Dabangg2","picUrl":"http:\/\/www.naz8.com\/images\/Dabangg2.jpg"},{"id":"2","name":"Talassh","picUrl":"http:\/\/www.naz8.com\/images\/talassh.jpg"},{"id":"3","name":"JAB TAK HAI JAAN","picUrl":"http:\/\/www.naz8.com\/images\/jthj.jpg"},{"id":"4","name":"Khiladi 786","picUrl":"http:\/\/www.naz8.com\/images\/khiladi786.jpg"}]}

我可以通过以下方式获取数据,以动态创建详细的列表视图:

<script type="text/javascript">

 $.getJSON("movie-details.json", function(movies){
   //Start off with an empty list every time to get the latest from server
   $('#movieList').empty();

   //add the movie items as list
   $.each(movies, function(i, movie){
     $('#movieList').append(generateMovieLink(movie));
   });

   //refresh the list view to show the latest changes
   $('#movieList').listview('refresh');

 });

  //creates a movie link list item
 function generateMovieLink(movie){

  //debugger;
  return '<li><a href="javascript:void(0)'
        + '" onclick="goToMovieDetailPage(\''
        + movie.name 
        + '\',\''
        + movie.picUrl +'\')">' 
        + movie.name 
        + '</a></li>';
 }

 function goToMovieDetailPage(movieName, moviePicUrl){

  //create the page html template
  var moviePage = $("<div data-role='page' data-url=dummyUrl><div data-role='header' data-add-back-btn='true'><h1>"
                  + movieName + "</h1></div><div data-role='content'><img border='0' src='" 
                  + moviePicUrl + "' width=204 height=288></img></div><div data-role='footer' data-position='fixed'><h4>" 
                  + movieName + "</h4></div></div>");

  //append the new page to the page container
  moviePage.appendTo( $.mobile.pageContainer );

  //go to the newly created page
  $.mobile.changePage( moviePage );
 }  

</script>

如何填充php文件中的数据,例如movie-details.php:

<?php
include('connection.php');
$var = array();
$sql = "SELECT * FROM movies";
$result = mysqli_query($con, $sql);

while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"movies":'.json_encode($var).'}';
?>

我需要声明哪些变量才能从php文件中的objet获取json数据?

例如:

//只是一个想法...我很困惑......

var url =“....”;

$。的getJSON(URL,函数(...){

$。each(movie.movi​​es,function(i,...)

非常感谢您的帮助......

2 个答案:

答案 0 :(得分:1)

你应该json编码整个shebang。

echo json_encode(array("movies" => $var));

对于jquery方法,$.getJSON('<url>', ...)将起作用。

答案 1 :(得分:0)

对我来说,最简单的方法就是从控制台中将数据视觉化为树。

$.getJSON(url, function(data){  
    console.log(data) 
});