简体   繁体   English

Ajax调用Yii2时发生跨域错误

[英]Cross domain error on Ajax call, Yii2

Here is simplified version of my probem. 这是我的探针的简化版本。

I try to make a simple ajax call on a view to specific controller/action url and expecting json response. 我尝试对特定的控制器/操作url进行查看,并期望json响应进行简单的ajax调用。

views/artwork/ajax.js 视图/图稿/ajax.js

ajaxRequest = $.ajax({
    type: "post",
    dataType: 'json',
    url: "/index.php?r=artwork/search",
    data: { "globalSearch": "somesearchterm" }
});

An action that correspond to the request, in this case, actionSearch , just simply return back the parameter's value globalSearch as response. 与请求相对应的操作(在本例中为actionSearch )只需返回参数的值globalSearch作为响应即可。

Controllers/ArtworkController.php 控制器/ArtworkController.php

public function actionSearch()
{
    if (Yii::$app->request->isAjax) {

        Yii::$app->response->format = Response::FORMAT_JSON;

        $sterm = Yii::$app->$request->post('globalSearch');

        $res = array(
            'logicresult' => $sterm,
            'success' => true,
        );

        return $res;
    }
}

However, I got an jquery crossdomain error. 但是,我遇到了一个jQuery跨域错误。 what have i done wrong? 我做错了什么?

Chrome Console Log Chrome控制台日志

POST http://localhost/index.php?r=artwork%2Fsearch 500 (Internal Server Error)
n.ajaxTransport.k.cors.a.crossDomain.send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4handleAjaxLink @ajax.js:19
n.event.dispatch @ jquery.min.js:3
n.event.add.r.handle @ jquery.min.js:3

The 500 (internal server error) means something went wrong on the server's side. 500(服务器内部错误)表示服务器方面出现了问题。

it is not cross domain error . 这不是跨域错误。 error is in your PHP code. 错误在您的PHP代码中。

you forgot to add close } for if condition ( AS per code mention in Question for action actionSearch ). 您忘记为if条件添加close } (按照操作问题actionSearch代码中提到的AS进行操作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM