因此,当我尝试将数据库对象数组返回到我的 AJAX 并解析它时,它会变成一个字符数组。我的意思是我的json_encode
结果是[{'id':38, 'first_name':jana}]
,当尝试将其解析为 ajax 中的数组时,发生的事情是和字符数组 - ['[', '{', ''']
等。这是我的 ajax:
function searchInput() {
var $content = $('.jobboard-quick-search-form').serialize();
$.ajax({
url : '/admin/site/search',
method : "GET",
data : $content,
success : function ( data ) {
var arr = JSON.parse(data);
console.log(arr);
}
});
}
和我的行动:
public function actionSearch()
{
$lang = frontendmodelsLang::getCurrent();
$pageSize = 100;
if(Yii::$app->request->isAjax)
{
$search = Yii::$app->request->get('search-label');
$town = Yii::$app->request->get('towns-list');
$startsWith = '%'.$search;
$between = '%'.$search.'%';
$endsWith = $search.'%';
$joinDoctors = "SELECT `doctor`.`id`, `doctorLang`.`first_name`, `doctorLang`.`second_name`, `doctorLang`.`city`, `doctorLang`.`hospital_name`
FROM `doctor` LEFT JOIN `doctorLang` ON `doctor`.`id`=`doctorLang`.`doc_id`
WHERE `doctorLang`.`city`='$town'
AND `doctorLang`.`language`='$lang->url'
AND `doctor`.`active`=1
AND (`doctorLang`.`first_name` LIKE '$startsWith'
OR `doctorLang`.`first_name` LIKE '$between'
OR `doctorLang`.`first_name` LIKE '$endsWith'
OR `doctorLang`.`second_name` LIKE '$startsWith'
OR `doctorLang`.`second_name` LIKE '$between'
OR `doctorLang`.`second_name` LIKE '$endsWith'
OR `doctorLang`.`third_name` LIKE '$startsWith'
OR `doctorLang`.`third_name` LIKE '$between'
OR `doctorLang`.`third_name` LIKE '$endsWith')";
$doctor = Yii::$app->db->createCommand($joinDoctors)->queryAll();
$joinHospitals = "SELECT `hospital`.`id`, `hospitalLang`.`title`, `hospitalLang`.`address`, `hospitalLang`.`description`
FROM `hospital` LEFT JOIN `hospitalLang` ON `hospital`.`id`=`hospitalLang`.`hospital_id`
WHERE `hospitalLang`.`city`='$town'
AND `hospitalLang`.`language`='$lang->url'
AND `hospital`.`active`=1
AND (`hospitalLang`.`title` LIKE '$startsWith'
OR `hospitalLang`.`title` LIKE '$between'
OR `hospitalLang`.`title` LIKE '$endsWith')";
return json_encode($doctor);
}
}
提前谢谢你!
首先添加 ajax:
dataType: 'json'
$.ajax({
url:<code>,
type: <code>,
dataType: 'json',
data:<code>
})
接下来尝试使用rest控制器
class DataController extends yiirestController
{
public function actionSearch()
{
[.....]
return Yii::$app->db->createCommand($joinDoctors)->queryAll();
}
}