我正在使用ajax在yii2中开发一个搜索栏。问题是Yii::$app->request->isAjax
属性始终返回false
这是我的行动:
public function actionAjaxsearch()
{
if(Yii::$app->request->isAjax)
{
$keywords = Yii::$app->request->queryParams;
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'data' => $keywords,
'code' => 200
];
}
else throw new \yii\web\HttpException(404, 'Page not found.');
这是我的剧本:
$('#search-box').keyup(function( event ){
event.preventDefault();
$.ajax({
url: 'http://localhost/items/ajaxsearch',
data: {keywords: $( '#search-box' ).val()},
type: 'GET',
dataType: 'json',
}).done(function(){
console.log('success');
}).fail(function( data ){
alert( data );
}).always(function(){
alert('finished');
})
});
如果我不使用if
和Yii::$app->request->isAjax
控制器,只需使用数据呈现JSON。
P.D #search-box
的内容已成功通过。
编辑@SilverFire
转储中没有一些
["HTTP_X_REQUESTED_WITH"] => not defined,
["HTTP_ACCEPT"]=> string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
["CONTENT_TYPE"] =>not defined,
["HTTP_CONTENT_TYPE"] =>not defined,
["REQUEST_METHOD"]=> string(3) "GET",
["HTTP_X_HTTP_METHOD_OVERRIDE"] =>not defined,
答案 0 :(得分:2)
嗯,由于某些原因,您的浏览器不会将CREATE TABLE routes (
RouteId SERIAL PRIMARY KEY,
Rating int not null
);
CREATE TABLE RouteFlights (
RouteFlightId serial primary key,
RouteId int not null references Routes(RouteId),
Flight int not null references Flights(FlightId)
);
标头发送到服务器。
它猜测它可能与:Missing X-Requested-With: XMLHttpRequest (causes 200 OK But Shows as Error?)和Cross-Domain AJAX doesn't send X-Requested-With header
有关