在 cakePHP 2.x 中,您的控制器需要以这种方式将 json 数据返回到 $.ajax 请求:
<?php
App::uses('AppController', 'Controller');
App::uses('JsBaseEngineHelper', 'View/Helper');
class AjaxtestsController extends AppController {
function beforeFilter() {
parent::beforeFilter();
}
public function returnsSomthing()
{
$layout = 'ajax'; // you need to have a no html page, only the data.
$this->autoRender = false; // no need to render the page, just plain data.
$data = array();
$jquerycallback = $_POST["callback"];
//do something and then put in $data those things you want to return.
//$data will be transformed to JSON or what you configure on the dataType.
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($data).',"ajt":','postfix' => '});'));
}
}
改进的答案
您可以使用控制器的方法在 db 上搜索数据:find(),但我将搜索查询移至模型:
第一:在型号代码处添加标记行
App::uses('AppModel', 'Model');
App::uses('Sanitize', 'Utility'); // <---
App::uses('JsBaseEngineHelper', 'View/Helper'); // <---
第二:创建一个执行搜索的Model方法:
public function getdata(){
$input = NULL;
$query = array();
$sql = NULL;
$data = array();
$i = 0;
$input = $_GET["name_startsWith"]; // <-- obtains the search parameter
$input = Sanitize::clean($input); // <-- prepares the search parameter
$sql = "select * from atable where condition like '".$input."%';";
$query = $this->query($sql); // <-- the model execute the search
if ($query){
$c = count($query);
for($i=0;$i<$c;$i++){ // <-- iterate over the returned data
$json['id'] = $query[$i][0]['id'];
$json['column1'] = $query[$i][0]['column1'];
$json['column2'] = $query[$i][0]['column2'];
$data[] = $json; // <-- the data it's stored on an multiarray, to be converted to JSON
}
}
$jquerycallback = $_GET["callback"];
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($query).',"search":','postfix' => '});')); //<-- the data it´s returned as JSON
}
然后:在控制器上创建一个方法来调用搜索
public function getdata()
{
$layout = 'ajax'; //<-- No LAYOUT VERY IMPORTANT!!!!!
$this->autoRender = false; // <-- NO RENDER THIS METHOD HAS NO VIEW VERY IMPORTANT!!!!!
$this->Cliente->getclient(); // <-- Get the data
}
您可以像这样通过 ajax 调用此方法:
$.ajax({
url: "/application/controller/getdata",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.search, function( item ) {
return {
value: item.id,
label: item.column1+" "+item.column2
}
}));
}
});
检查此以获取更多信息: