如何从包含 JSON 编码的 html 字符串的 javascript 数组中的每个元素中删除引号,这些字符串从具有 php 的 mysql 数据库返回
How to remove quotes from each element in a javascript array containing JSON encoded html strings returned from a mysql database with php
Ajax 使用 data1.php 文件和 pdo returns hmtl 字符串调用 mysql 数据库,这些字符串被放入数组中,用 json 编码并发送到 ajax 响应函数以在 html 中显示。当然数组中的元素有标签和引号,很难去掉。到目前为止最简单和最接近的解决方案是用 javascript .replace() 替换字符串中的引号。这不适用于数组的数组,除非引用了单个元素。有什么办法解决这个问题?这是代码。
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
}
响应函数:
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
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)
?>
注意:这会查询通过 xampp 提供的本地主机数据库。这不是全部代码,但除以下代码外一切正常:
1) table_2 = data.data.replace(/"/g,"");
returns '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>
这样就可以了。
3) 在控制台中仅在 console.log(table_3);
returns 中进行类似评论:
</table>
这样也可以。
4) 如果在 table_2 = data.data;
中注释并在控制台中输入 table_2 结果是:
undefined
5) 尝试使用此代码从数组数组中删除引号:
a) 在页面的 js 初始化文件中放置一个函数:
function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
并在响应回调函数创建的数据对象中的数据数组上使用该函数(所以 x = data.data)
结果未定义,无效。
JSON.parse(table_1);
立即遇到 <
并且不会解析数据数组中的任何字符串(table_2 或 table 3) .
添加 JSON_HEX_QUOT | JSON_HEX_TAG
无效。
据推测,使用函数遍历数组 data.data 并使用 .replace() 和 reg exp 将引号替换为空应该是最简单的解决方案。关于如何在 ajax 回调返回的数组中循环遍历 json_encoded 数组的 html 字符串的任何提示?
不要在任何地方替换任何东西。您唯一需要做的就是在构建 HTML 字符串时添加 htmlspecialchars()
。
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = '<tr><td>'.htmlspecialchars($r['id'])
.'</td><td>'.htmlspecialchars($r['phone_number'])
.'</td></tr>';
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));
然后,当你收到这样的JSON,直接把它原样放入HTML即可。
$('table#display').html(received_data.table_rows);
但是有更好的方法来实现它。 -- 通过 JSON 仅发送没有标记的数据并在 JS 中构建标记:
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = [
'id' => $r['id'],
'phone_number' => $r['phone_number']
];
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));
然后:
// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
var r = received_data.table_rows[i];
$table.append($('<tr>')
.append($('td').text(r.id))
.append($('td').text(r.phone_number))
);
}
PHP 案例 0,从 ajax 下拉选择器表单提交调用的文件:
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
include "db_connect_df_test.php";
//switch statement for mysql queries based on dropdown selected
switch($topic_2){
case "Address":
//set response variable
$ret_s['response'] = 0;
// select organization address
$sql = "SELECT IFNULL(ID, '--') AS ID,
IFNULL(Organization, '--') AS Organization,
IFNULL(Contact_Names, '--') AS Contact_Names,
IFNULL(City, '--') City,
IFNULL(Street, '--') AS Street,
IFNULL(Unit, '--') AS Unit,
IFNULL(Postal_Code, '--') AS Postal_Code,
IFNULL(Region, '--') AS Region,
IFNULL(Country, '--') AS Country,
IFNULL(ts, '--') AS ts
FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
// extract table rows
foreach($result as $row){
$ret_d[$row_1] = [
'Id'=> $row['ID'],
'Organization' => $row['Organization'],
'Contact_Names' => $row['Contact_Names'],
'City'=> $row['City'],
'Street'=> $row['Street'],
'Unit' => $row['Unit'],
'Postal_Code' => $row['Postal_Code'],
'Region' => $row['Region'],
'Country'=> $row['Country'],
'Date'=> $row['ts']
];//end load data from data base
$row_1++;
}//end table data as rows
break;
Javascript 初始化文件,ajax 响应函数的 case 0 部分:
function processResult_L(data, textStatus){
// Required Callback Function
//create dom elements for table head and body
//to check variables in dev console remove 'var'(make public)
var $table = $("<table id='display_table'>");
$table.append($('<tbody>'));
//create response array
var response = {};
response = data['status']['response'];
//create row array for building table data
var r = [];
switch(response){
case 0: /*Address case */
// build table header
$table.append($('<tr>')
.append($('<th>').text('ID'))
.append($('<th>').text('Organization'))
.append($('<th>').text('Contact'))
.append($('<th>').text('City'))
.append($('<th>').text('Street'))
.append($('<th>').text('Unit'))
.append($('<th>').text('Post Code'))
.append($('<th>').text('Region'))
.append($('<th>').text('Country'))
.append($('<th>').text('Date')));
// build table content
for(var i = 0; i < data.table_rows.length; i++) {
r[i] = data.table_rows[i];
$table.append($('<tr>')
.append($('<td>').text(r[i].Id))
.append($('<td>').text(r[i].Organization))
.append($('<td>').text(r[i].Contact_Names))
.append($('<td>').text(r[i].City))
.append($('<td>').text(r[i].Street))
.append($('<td>').text(r[i].Unit))
.append($('<td>').text(r[i].Postal_Code))
.append($('<td>').text(r[i].Region))
.append($('<td>').text(r[i].Country))
.append($('<td>').text(r[i].Date))
); // end append table content
} // end build table content
break;
Ajax 使用 data1.php 文件和 pdo returns hmtl 字符串调用 mysql 数据库,这些字符串被放入数组中,用 json 编码并发送到 ajax 响应函数以在 html 中显示。当然数组中的元素有标签和引号,很难去掉。到目前为止最简单和最接近的解决方案是用 javascript .replace() 替换字符串中的引号。这不适用于数组的数组,除非引用了单个元素。有什么办法解决这个问题?这是代码。
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
}
响应函数:
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
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)
?>
注意:这会查询通过 xampp 提供的本地主机数据库。这不是全部代码,但除以下代码外一切正常:
1) table_2 = data.data.replace(/"/g,"");
returns '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>
这样就可以了。
3) 在控制台中仅在 console.log(table_3);
returns 中进行类似评论:
</table>
这样也可以。
4) 如果在 table_2 = data.data;
中注释并在控制台中输入 table_2 结果是:
undefined
5) 尝试使用此代码从数组数组中删除引号:
a) 在页面的 js 初始化文件中放置一个函数:
function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
并在响应回调函数创建的数据对象中的数据数组上使用该函数(所以 x = data.data)
结果未定义,无效。
JSON.parse(table_1);
立即遇到 <
并且不会解析数据数组中的任何字符串(table_2 或 table 3) .
添加 JSON_HEX_QUOT | JSON_HEX_TAG
无效。
据推测,使用函数遍历数组 data.data 并使用 .replace() 和 reg exp 将引号替换为空应该是最简单的解决方案。关于如何在 ajax 回调返回的数组中循环遍历 json_encoded 数组的 html 字符串的任何提示?
不要在任何地方替换任何东西。您唯一需要做的就是在构建 HTML 字符串时添加 htmlspecialchars()
。
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = '<tr><td>'.htmlspecialchars($r['id'])
.'</td><td>'.htmlspecialchars($r['phone_number'])
.'</td></tr>';
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));
然后,当你收到这样的JSON,直接把它原样放入HTML即可。
$('table#display').html(received_data.table_rows);
但是有更好的方法来实现它。 -- 通过 JSON 仅发送没有标记的数据并在 JS 中构建标记:
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = [
'id' => $r['id'],
'phone_number' => $r['phone_number']
];
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));
然后:
// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
var r = received_data.table_rows[i];
$table.append($('<tr>')
.append($('td').text(r.id))
.append($('td').text(r.phone_number))
);
}
PHP 案例 0,从 ajax 下拉选择器表单提交调用的文件:
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
include "db_connect_df_test.php";
//switch statement for mysql queries based on dropdown selected
switch($topic_2){
case "Address":
//set response variable
$ret_s['response'] = 0;
// select organization address
$sql = "SELECT IFNULL(ID, '--') AS ID,
IFNULL(Organization, '--') AS Organization,
IFNULL(Contact_Names, '--') AS Contact_Names,
IFNULL(City, '--') City,
IFNULL(Street, '--') AS Street,
IFNULL(Unit, '--') AS Unit,
IFNULL(Postal_Code, '--') AS Postal_Code,
IFNULL(Region, '--') AS Region,
IFNULL(Country, '--') AS Country,
IFNULL(ts, '--') AS ts
FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
// extract table rows
foreach($result as $row){
$ret_d[$row_1] = [
'Id'=> $row['ID'],
'Organization' => $row['Organization'],
'Contact_Names' => $row['Contact_Names'],
'City'=> $row['City'],
'Street'=> $row['Street'],
'Unit' => $row['Unit'],
'Postal_Code' => $row['Postal_Code'],
'Region' => $row['Region'],
'Country'=> $row['Country'],
'Date'=> $row['ts']
];//end load data from data base
$row_1++;
}//end table data as rows
break;
Javascript 初始化文件,ajax 响应函数的 case 0 部分:
function processResult_L(data, textStatus){
// Required Callback Function
//create dom elements for table head and body
//to check variables in dev console remove 'var'(make public)
var $table = $("<table id='display_table'>");
$table.append($('<tbody>'));
//create response array
var response = {};
response = data['status']['response'];
//create row array for building table data
var r = [];
switch(response){
case 0: /*Address case */
// build table header
$table.append($('<tr>')
.append($('<th>').text('ID'))
.append($('<th>').text('Organization'))
.append($('<th>').text('Contact'))
.append($('<th>').text('City'))
.append($('<th>').text('Street'))
.append($('<th>').text('Unit'))
.append($('<th>').text('Post Code'))
.append($('<th>').text('Region'))
.append($('<th>').text('Country'))
.append($('<th>').text('Date')));
// build table content
for(var i = 0; i < data.table_rows.length; i++) {
r[i] = data.table_rows[i];
$table.append($('<tr>')
.append($('<td>').text(r[i].Id))
.append($('<td>').text(r[i].Organization))
.append($('<td>').text(r[i].Contact_Names))
.append($('<td>').text(r[i].City))
.append($('<td>').text(r[i].Street))
.append($('<td>').text(r[i].Unit))
.append($('<td>').text(r[i].Postal_Code))
.append($('<td>').text(r[i].Region))
.append($('<td>').text(r[i].Country))
.append($('<td>').text(r[i].Date))
); // end append table content
} // end build table content
break;