Yii2:isAjax返回false

时间:2015-12-09 10:55:19

标签: php jquery ajax yii2

我正在使用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');
    })
});

如果我不使用ifYii::$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,

1 个答案:

答案 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

有关