简体   繁体   中英

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.

views/artwork/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.

Controllers/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. what have i done wrong?

Chrome Console Log

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.

it is not cross domain error . error is in your PHP code.

you forgot to add close } for if condition ( AS per code mention in Question for action actionSearch ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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