안녕하세요. 여기에서 질문을 통해 검색했지만 아무것도 찾을 수 없습니다. 저는 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;`
응답을 주셔서 감사합니다. 질문에 추가 된 코드를보고 올바른 방향으로 나를 가리켜 주시겠습니까? 감사! –
내 대답을 살펴보면 배열을 사용하지 않고도 똑같은 작업을 수행 할 수 있습니다. 그래서'echo json_encode ($ html);'그리고 나서'$ data'를 통해 성공 함수에 접근 할 수 있습니다. – anomareh
감사합니다! json_encode 배열은 내가 필요한 것이다. –