Yii2:isAjax返回false [英] Yii2: isAjax returns false

查看:214
本文介绍了Yii2:isAjax返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ajax在yii2中开发一个搜索栏.问题是Yii::$app->request->isAjax属性始终返回false

Im developing a search bar in yii2 using ajax. The problem is the Yii::$app->request->isAjax property always returns 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.

If i dont use the if with Yii::$app->request->isAjax the controller just render the JSON with the data.

P.D #search-box的内容已成功传递.

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

编辑为@SilverFire

Edit to @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标头发送到服务器.

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

它可能与以下内容有关:跨域AJAX不会发送X-Requested-With标头

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

这篇关于Yii2:isAjax返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆