2010-01-17 2 views
14

안녕하세요. 여기에서 질문을 통해 검색했지만 아무것도 찾을 수 없습니다. 저는 PHP와 jQuery를 처음 사용하기 때문에 저와 잘 지내십시오.PHP 스크립트에서 JSON 및 HTML을 반환합니다.

내가 뭘하려는 건 내 데이터베이스에서 데이터에 대한 MySQL의 쿼리를 실행하고 PHP의 json_encode를 사용하여 JSON 형식으로 직렬화 내 스크립트에 jQuery를 사용하여 아약스 요청을 보내려고합니다. 응답은 사용 가능한 json2.js 스크립트로 구문 분석됩니다. 이 모든 것은 잘 작동하지만이 스크립트에서 JSON 이외의 다른 데이터도 반환하고 싶습니다.

주로, 나는 또한로 json_encode 전에 다음 줄 에코 싶습니다 그러나

echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>"; 

을 내 jQuery를이 json.parse 기능으로 인해 실패하고, 아약스 성공시 전체 응답을 평가하고있다 스크립트의 반환 형식이 잘못되었습니다.

 success: function(data) { 
      //retrieve comments to display on page by parsing them to a JSON object 
      var obj = JSON.parse(data); 
        //loop through all items in the JSON array 
        for (var x = 0; x < obj.length; x++) { 
         //Create a container for the new element 
         var div = $("<div>").addClass("bubble").appendTo("#comments"); 
         //Add author name and comment to container 
         var blockquote = $("<blockquote>").appendTo(div); 
          $("<p>").text(obj[x].comment).appendTo(blockquote); 
         var cite = $("<cite>").appendTo(div); 
          $("<strong>").text(obj[x].name).appendTo(cite); 
          $("<i>").text(obj[x].datetime).appendTo(cite); 
        } 
       $("#db").attr("value", '' + initialComments + ''); 
    } 
난 그냥 JSON 인구 이상이 스크립트를 사용하기로 json_encode뿐만 아니라 HTML 라인을 반환 할 수있는 방법을

사람이 알고 있나요?

thankyou,이 웹 사이트는 내 멍청한 질문에 답하는 데 훌륭했습니다.

내 PHP는`

for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) { 
$row = mysql_fetch_assoc($result); 
    $comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));   
} 

//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>"; 

$response = json_encode($comments); 
echo $response;` 

답변

19

은하지 echo 라인을 수행 변수에 저장합니다. $response = array( 'html' => $the_line_you_wanted_to_echo, 'jsobject' => $the_object_you_were_going_to_send_back ); 간단한 배열을 만들고 그 대신에 (json_encode 경유로) 보냅니다.

또한 json2.js가 필요하지 않으며 jQuery는 탁월한 JSON 파서를 제공합니다. 이 $.get('your/url', { params : here }, success, 'JSON');

가 새로 도입 반복 일치하도록 변경 같은

당신은로드 할 수 있습니다.

for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) { 
    $row = mysql_fetch_assoc($result); 
    $comments[$x] = array(
     "name" => stripslashes($row["name"]), 
     "comment" => stripslashes($row["comment"]), 
     "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])) 
    );   
} 

$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>"; 

echo json_encode(array('comments' => $comments, 'html' => $html)); 

다음, 자바 스크립트, 당신은

function success(parsedObject){ 
    parsedObject.html; // "<h1 style..." 
    parsedObject.comments; // an array of objects 
    parsedObject.comments[0].name 
    + " on " + parsedObject.comments[0].datetime 
    + " said \n" + parsedObject.comments[0].comment; // for example 
} 
+0

응답을 주셔서 감사합니다. 질문에 추가 된 코드를보고 올바른 방향으로 나를 가리켜 주시겠습니까? 감사! –

+0

내 대답을 살펴보면 배열을 사용하지 않고도 똑같은 작업을 수행 할 수 있습니다. 그래서'echo json_encode ($ html);'그리고 나서'$ data'를 통해 성공 함수에 접근 할 수 있습니다. – anomareh

+0

감사합니다! json_encode 배열은 내가 필요한 것이다. –

5

으로 그냥 다시 배열받을 수 있도록 인코딩 할 모든 데이터를 넣어 위 말했다.

<?php 

echo json_encode(array(
    'html' => $html, 
    'foo' => $bar, 
    'bar' => $baz 
)); 

?> 

마찬가지로 json2.js는 필요하지 않습니다. 데이터 유형을 json으로 지정하여 jQuery의 모든 ajax 함수로 JSON 데이터를 파싱 할 수있다.

$.ajax({ 
    type: 'POST', 
    url: 'path/to/php/script.php', 
    dataType: 'json', 
    data: 'foo=bar&baz=whatever', 
    success: function($data) { 
     var html = $data.html; 
     var foo = $data.foo; 
     var bar = $data.bar; 

     // Do whatever. 
    } 
}); 

편집 거의 어떤 Horia 말했다. 내가 볼 수있는 유일한 다른 변이는 동일한 배열에 모든 것을 원한다면입니다.예를 들어

:

PHP :

<?php 

// You have your comment array sent up as you want as $comments 
// Then just prepend the HTML string onto the beginning of your comments array. 
// So now $comments[0] is your HTML string and everything past that is your comments. 
$comments = array_unshift($comments, $your_html_string); 

echo json_encode($comments); 

?> 

jQuery를 :

$.ajax({ 
    type: 'POST', 
    url: 'path/to/php/script.php', 
    dataType: 'json', 
    data: 'foo=bar&baz=whatever', 
    success: function($comments) { 
     // Here's your html string. 
     var html = $comments[0]; 

     // Make sure to start at 1 or you're going to get your HTML string twice. 
     // You could also skip storing it above, start at 0, and add a bit to the for loop: 
     // if x == 0 then print the HTML string else print comments. 
     for (var x = 1; x < $comments.length; x++) { 
      // Do what you want with your comments. 
      // Accessed like so: 
      var name = $comments[x].name; 
      var comment = $comments[x].comment; 
      var datetime = $comments[x].datetime; 
     } 
    } 
}); 
+0

해답을 주셔서 감사합니다. -하지만, 이제 html은 for 루프에 포함 된 배열로 인해 데이터베이스의 모든 항목에 대해 반복 처리됩니다. 거기에 HTML에서 코드를 한 번만 표시하는 json을 생성하기 위해 단일 html 변수에 db의 정보 배열을 결합 할 수있는 방법이 있습니까? –

+0

당신이 찾고 있던 것에 대한 답을 업데이트했습니다. – anomareh

0

당신은 jLinq, 당신은 자바 스크립트 객체를 조회 할 수있는 자바 스크립트 라이브러리에 관심이있을 수 있습니다. 샘플 쿼리는 다음과 같습니다.

var results = jLinq.from(data.users) 
    .startsWith("first", "a") 
    .orEndsWith("y") 
    .orderBy("admin", "age") 
    .select(); 

jLinq는 중첩 된 개체를 쿼리하고 조인을 지원합니다. 예를 들어 :

var results = jLinq.from(data.users) 
    .join(data.locations, //the source array 
     "location", //the alias to use (when joined) 
     "locationId", // the location id for the user 
     "id" // the id for the location 
    ) 
    .select(function(r) { 
     return { 
      fullname:r.first + " " + r.last, 
      city:r.location.city, 
      state:r.location.state 
     }; 
    }); 
관련 문제