을 호출합니다. pdo를 사용하여 data1.php 파일을 사용하여 mysql 데이터베이스에 Ajax 호출하면 hmtl 문자열이 배열로 반환되고, json으로 인코딩되고 html로 표시하기 위해 ajax 응답 함수로 전송됩니다. 물론 배열의 요소에는 제거하기 어려운 태그와 인용문이 있습니다. 지금까지 가장 쉽고 가장 가까운 해결책은 문자열의 따옴표를 javascript .replace()로 대체하는 것입니다. 단일 요소가 참조되지 않으면 배열 배열에 대해 작동하지 않습니다. 이 주변의 방법은 무엇입니까? 여기에 코드가 있습니다.JSON 인코딩 된 HTML 문자열을 포함하는 자바 스크립트 배열의 각 요소에서 PHP를 사용하여 mysql 데이터베이스에서 반환 된
Ajax 호출 :
function processForm_L(){
var topic = $("#topic").val();
// send data
$.ajax({
url: "../php/get_data1.php",
data: {
topic1:topic},
type: 'POST',
dataType: 'json',
success: processResult_L
}); // end .onclick
}
응답 기능 : get_data1.php
<?php
$ret_s = Array();//return status
$ret_t = Array();//return table
$ret_d = Array();//return data
$result = Array();
$row_1 = 1;
if(!empty($_POST)){
try{
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
// select everything from the raw_data database
$sql = "SELECT * FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
//set response variable
$ret_s['response'] = 1;
//table header
$ret_t['a'] ="<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>";
//fetch each row from database as html
foreach($result as $row){
$ret_d[$row_1] = "<tr>" ."<td>" . $row['ID'] . "</td>" ."<td>" .
$row['Organization'] . "</td>" ."<td>" . $row['Telephone'] . "</td>" . "<td>" . $row['Email'] . "</td>" ."<td>" . $row['Website'] . "</td>" ."<td>" . $row['Country'] . "</td>" ."<td>" . $row['Region'] . "</td>" ."<td>" . $row['City'] . "</td>" ."<td>" . $row['Street'] . "</td>" ."<td>" . $row['Unit'] . "</td>" ."<td>" . $row['Postal_Code'] . "</td>" ."<td>" . $row['Topic'] . "</td>" ."<td>" . $row['Message'] . "</td>" ."<td>" . $row['ts'] . "</td>" ."</tr>";
$row_1++;
}
// end table tag
$ret_t['b'] = "</table>";
//echo and encode array
echo json_encode(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d),JSON_HEX_QUOT|JSON_HEX_TAG);
// echo json_encode(stripslashes_nested(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d)),JSON_HEX_QUOT|JSON_HEX_TAG);
}//end connect
}//end try
catch (PDOException $e) {
$error16 = '<span class="error_s">Try again another time.</span>';
$error17 = '<span class="error_s">ERROR:' . $e->getMessage();
$ret_s['response'] = 0;
$ret_s['error'] = $error16 . $error17;
echo json_encode($ret_s);
} //end failure
}//end if is !empty($_POST)
?>
주
function processResult_L(data, textStatus){
// Required Callback Function
if(data['status']['response'] == 1){
//if(data[0] == 1){
table_1 = [];
table_2 = [];
table_3 = [];
table_1 = data.table['a'].replace(/"/g,"");
table_2 = data.data.replace(/"/g,"");
table_3 = data.table['b'].replace(/"/g,"");
//table_1 = JSON.parse(data.table['a']);
//table_2 = JSON.parse(data.data);
//table_3 = JSON.parse(data.table['b']);
//console.log(table_1);
console.log(table_2);
//console.log(table_3);
}//end if response == 1
else if(data.response == 0){
//var response = data + textStatus;
var table_4 = data.error;
$('#display').html(table_4);
}//end if response==0
}//end process results
쿼리 부분이는 로컬 호스트 데이터베이스가 XAMPP를 통해 게재 된 쿼리합니다. 이 모든 코드가 아니라 모든는 다음을 제외하고 잘 작동 : 배열 객체가 아닌 문자열
에게이기 때문에)
1) table_2 = data.data.replace(/"/g,"");
반환 'data.data.replace (함수 아니다 2) 콘솔에서 console.log(table_1);
결과 만 위의 주석 및 주석이있는 경우
<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>
이렇게 작동합니다. 유사 콘솔에서만 console.log(table_3);
반환에 주석
3) :
</table>
4) table_2 = data.data;
의 의견 및 콘솔 결과에 table_2를 입력 할 경우 :
A) 기능을 넣어 :
undefined
5) 배열의 배열에서 따옴표를 제거하려면이 코드를 시도 페이지의 js 초기화 파일에서 :
function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
데이터 오브젝트의 데이터 배열에서 해당 함수를 사용하십시오. 응답 콜백 함수 (x = data.data)에 의해 생성 된 t는
결과는 정의되어 있지 않으며 작동하지 않습니다.
JSON.parse(table_1);
은 바로 <
으로 실행되고 데이터 배열의 모든 문자열 (table_2 또는 table 3)에 대해 구문 분석되지 않습니다.
JSON_HEX_QUOT | JSON_HEX_TAG
이 추가되지 않았습니다.
아마도 함수를 사용하여 data.data 배열을 반복하고 .replace() 및 reg exp를 사용하여 인용 부호를 아무것도 대체하지 않는 것이 가장 쉬운 해결책이 될 것입니다. 배열에서 html 문자열의 json_encoded 배열을 반복하는 방법에 대한 정보는 ajax 콜백에서 반환됩니까?
이것은 효과가 있습니다. 감사. 원래 PHP에서 .htmlspecialchars()를 테스트하는 대신 양식 구성을 클라이언트 측으로 이동하고 jquery dom 요소를 작성했습니다. php와 javascript init에 switch 문을 추가하여 테이블에서 다른 쿼리를 선택했습니다. –
mysql 질의에서 null 값을 문자열로 대체하는 말도 안되는 점이 있습니다. PHP 행 빌드 함수에서보다 효율적으로 수행 할 수 있지만 작동합니다. 아래의 경우 switch 문과 다른 사람들이 볼 수있는 작업 코드 중 0입니다. –
기술적으로 질문에 답을 얻지 못했지만 더 나은 방법이 제공되었습니다. 아마도, ajax 호출을 통해 반환 된 json 데이터에서 큰 따옴표를 제거하려면 위에 제공된 for 루프를 사용하고 .replace()를 사용하여 두 번째 차원 배열을 반복 할 수 있습니다. –