jQuery / JavaScript를 사용하여 PHP 파일에서 ajax 응답으로 전송 된 JSON 문자열을 구문 분석하려고합니다.
Ajax 호출 :
<script>
$(document).ready(function(){
var query = $("#editor").html().replace(/(<([^>]+)>)/ig,"");
$.ajax({
type: "POST",
url: "app/query_db.php",
data: "q="+query,
success: function(resp){
if(resp) {
alert("Response : "+resp);
$("#res_data").html(resp);
}
else{
alert("Response: Failed")
}
});
return false;
});
});
</script>
PHP 파일 :
$db_conn = new db_connect();
$conn = $db_conn->connectToDB($DBHost,$DBName,$DBUser,$DBPwd);
$query_res = array();
if (fill_numeric_array_with_query_assoc($query_res, $sql_query, $conn)) { // Function to execute the query and fill the result
//do nothing
} else {
echo("Error description: " . mysqli_error($conn)); // Error message to display if failed to fetch the data
exit();
}
$data = json_encode($query_res);
echo $data;
Result: [{"uid":"admin","pwd":"xyz"},{"uid":"guest","pwd":"abc"}]
위의 JSON 문자열을 구문 분석하려고 할 때마다 0과 1이 키로, 다른 것은 값으로 끝납니다. 이상한 점은이 결과를 복사하여 JavaScript의 변수에 할당하면 문자열을 올바르게 구문 분석한다는 것입니다.
AJAX 응답으로 구문 분석하려고 할 때 무엇이 잘못되었는지 알지 못합니다.
JSON 문자열을 AJAX 응답으로 구문 분석 할 때 테이블 형식 :
자바 스크립트에서 변수에 할당 될 때 응답 :
uid pwd
admin xyz
guest abc
이것은 데이터를 가져와 각 개체를 테이블의 행으로 바꿉니다. #res_data
빈 <table>
요소 라고 가정하겠습니다 .
$.ajax({
type: "POST",
url: "app/query_db.php",
data: "q=" + query,
dataType: "json",
success: function(resp) {
if (resp) {
alert("Response : " + resp);
$("#res_data").empty();
if (resp.length > 0) {
var header = "<tr>";
for (var key in resp[0]) {
"<th>" + key + "</th>";
}
header += "</tr>";
$("#res_data").append(header);
var rows = "";
for (var i=0; i< resp.length;i++) {
rows += "<tr><td>" + resp[i].uid + "</td><td>" + resp[i].pwd + "</td></tr>";
}
$("#res_data").append(rows);
}
else { alert("No data returned"); }
} else {
alert("Response: Failed")
}
}
});
추가 ajax 옵션에 유의하십시오 dataType: "json"
.. 이건 중요하다. PHP는 응답을 JSON으로 해석하도록 클라이언트에 알리는 헤더를 보내지 않으므로 텍스트로 해석 할 가능성이 높습니다. 따라서 dataType:"json"
jQuery가 수행 할 작업을 알고 응답을 JS 객체에 직접 생성 하도록 추가 해야합니다. 그러면 문제가 없어야합니다. 그렇지 않은 경우 문자열로보고 한 번에 한 문자 씩 반복하여 질문에서 보여준 이상한 출력을 생성합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다