Yii2: isAjax returns false


Yii2: isAjax returns false

我使用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,

由于某些原因,您的浏览器不会将HTTP_X_REQUESTED_WITH标头发送到服务器。

它猜测这可能与:缺少X-Requested-With:XMLHttpRequest(导致200 OK但显示为错误?)和跨域AJAX不相关;t发送带有标头的X-Requested