Yii2: isAjax returns false

浪子不回头ぞ 提交于 2019-12-07 20:31:55

问题


Im developing a search bar in yii2 using ajax. The problem is the Yii::$app->request->isAjax property always returns false

This is my action:

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.');

And this is my script:

$('#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 i dont use the if with Yii::$app->request->isAjax the controller just render the JSON with the data.

P.D The content of #search-box is succesfully passed.

Edit to @SilverFire

Dont have some in the dump

["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:


Well, your browser for some reasons does not send the HTTP_X_REQUESTED_WITH headers to the server.

It guess it might be related to: Missing X-Requested-With: XMLHttpRequest (causes 200 OK But Shows as Error?) and Cross-Domain AJAX doesn't send X-Requested-With header



来源:https://stackoverflow.com/questions/34177008/yii2-isajax-returns-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!