我有这个ajax代码,它将在Success块中返回MySql的结果。
$.ajax({
type:"POST",
url:"index.php",
success: function(data){
alert(data);
}
});
我的查询
$sql = "SELECT * FROM tablename";
$rs=parent::_executeQuery($sql);
$rs=parent::getAll($rs);
print_r($rs);
return $rs
My Response Array警告Success AJAX
Array
(
[0] => Array
(
[section_id] => 5
[version] => 1
[section_name] => Crop Details
[id] => 5
[document_name] => Site Survey
[document_master_id] => 1
[document_section_id] => 5
)
[1] => Array
(
[section_id] => 28
[version] => 1
[section_name] => Vegetative Report
[id] => 6
[document_name] => Site Survey
[document_master_id] => 1
[document_section_id] => 28
)
)
我想从结果中只获取 section_name 和 document_name ,以便我可以将这两个值附加到我的列表中。
答案 0 :(得分:3)
请勿使用print_r()
返回回复,请使用json_encode()
:
echo json_encode($rs);
然后在Javascript中,你可以这样做:
$.ajax({
type:"POST",
url:"index.php",
dataType: 'json'
success: function(data){
for (var i = 0; i < data.length; i++) {
console.log(data[i].section_name, data[i].document_name);
}
}
});
答案 1 :(得分:2)
使用
更改您的选择查询$sql = "SELECT section_name,document_name FROM tablename";
答案 2 :(得分:2)
$sql = "SELECT * FROM tablename";
$rs=parent::_executeQuery($sql);
$rs=parent::getAll($rs);
return json_encode($rs);
的index.php
$.ajax({
type:"POST",
url:"index.php",
success: function(data){
alert(data);
var data = JSON.parse(data);
/* you can use $.each() function here */
}
});
答案 3 :(得分:1)
这样做:
$sql = "SELECT * FROM tablename";
$rs=parent::_executeQuery($sql);
$rs=parent::getAll($rs);
$resp = array();
foreach( $rs as $each ){
$resp[]['section_name'] = $each['section_name'];
$resp[]['document_name'] = $each['document_name'];
}
return json_encode($resp);
像这样访问JSON响应:
for (var i = 0; i < data.length; i++) {
console.log(data[i].section_name, data[i].document_name);
}