2008-11-29 2 views
18

jQuery를 사용하여 Ajax 호출을 통해 내 페이지에 결과를 표시하는 가장 좋은 방법을 찾으려는 경우 가장 좋은 방법은 JSON 또는 일반 텍스트로 전달하는 것입니다. 이전에 아약스 호출을 사용했지만 어느 것이 더 선호되는지, JSON 버전의 경우 결과를 표시하기 위해 PHP 페이지에서 생성 된 JSON 파일을 읽는 가장 좋은 방법은 무엇인가?jQuery를 사용하여 JSON을 통해 데이터를 표시하는 가장 좋은 방법

내가 모두 표시하기 위해 실행하려면 .each을 포함 할 것입니다.

+0

컬린/라이언, 편집 당신에게 제이 감사, 아래에있는 내 HTML입니다 귀하의 질문은 아래의 토론을 반영합니다. 답변 섹션은 토론 용으로 설계된 것이 아니며 (그 목적을 위해 의견을 사용하거나 추가 세부 정보로 질문을 업데이트하십시오). –

답변

26

뭔가 :

$.getJSON("http://mywebsite.com/json/get.php?cid=15", 
     function(data){ 
      $.each(data.products, function(i,product){ 
      content = '<p>' + product.product_title + '</p>'; 
      content += '<p>' + product.product_short_description + '</p>'; 
      content += '<img src="' + product.product_thumbnail_src + '"/>'; 
      content += '<br/>'; 
      $(content).appendTo("#product_list"); 
      }); 
     }); 

제품의 키를 반환 된 PHP 배열로 만든 JSON 객체를 걸릴 것입니다. 예컨대 :

$("#product_list").empty(); 

을 그리고 새로운 매개 변수를 다시해서 getJSON 전화 :

Array('products' => Array(0 => Array('product_title' => 'Product 1', 
            'product_short_description' => 'Product 1 is a useful product', 
            'product_thumbnail_src' => '/images/15/1.jpg' 
            ) 
          1 => Array('product_title' => 'Product 2', 
            'product_short_description' => 'Product 2 is a not so useful product', 
            'product_thumbnail_src' => '/images/15/2.jpg' 
            ) 
         ) 
    ) 

간단하게 할 당신이하고자 목록을 다시로드합니다.

+2

$ (content) .appendTo ("# product_list")가 루프 외부에 있어야한다는 성능상의 이유로. DOM에 추가하는 것은 느리며 한 번만 수행해야합니다. –

+0

예, 그렇습니다. 첫 번째 줄은 content + =이어야합니다. 그러나 DOM에 추가하는 것은 다른 사람보다 일부 브라우저에서 더 빨리 : – Jay

10

JQuery는 Ajax 용 내장 json 데이터 유형이 있으며 데이터를 오브젝트로 변환합니다. PHP %에는 또한 배열을 json 형식의 문자열로 변환하는 inbuilt json_encode 함수가 있습니다. 많은 파싱, 디코딩 노력을 절약합니다.

3

당신은 JSON 객체에서의 jQuery 개체를 만들 수 있습니다 :이 같은

$.getJSON(url, data, function(json) { 
    $(json).each(function() { 
     /* YOUR CODE HERE */ 
    }); 
}); 
4

Perfect!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title> 
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" /> 
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" /> 
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]--> 
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" /> 
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> 
<script type="text/javascript"> 
/* <![CDATA[ */ 
$(document).ready(function(){ 
    $.getJSON("readJSON.php",function(data){ 
     $.each(data.post, function(i,post){ 
      content += '<p>' + post.post_author + '</p>'; 
      content += '<p>' + post.post_content + '</p>'; 
      content += '<p' + post.date + '</p>'; 
      content += '<br/>'; 
      $(content).appendTo("#posts"); 
     }); 
    }); 
}); 
/* ]]> */ 
</script> 
</head> 
<body> 
     <div class="container"> 
       <div class="span-24"> 
         <h2>Check out the following posts:</h2> 
         <div id="posts"> 
         </di> 
       </div> 
     </div> 
</body> 
</html> 

그리고 내 JSON 출력 : 내 코드를 실행하면 나는,이 오류가

{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]} 

:

object is undefined 
http://localhost:8888/rks/post/js/jquery.js 
Line 19 
+0

내가 그것을 가지고, 내가 변경 : \t \t $ .each (data.posts, 기능 (전, 후) { 을 그래서 data.post -> 데이터 . 포스트 – Coughlin

관련 문제