设置URL规则后,yii2 ajax调用不再有效

时间:2020-12-07 20:14:07

I setup ajax function that is called when a button is clicked.

我设置了一个单击按钮时调用的ajax函数。

It works when there no rule rules however when I set the below URL manager rules

当没有规则规则时,它可以工作,但是当我设置以下URL管理器规则时

'posts' => 'posts/index',
'posts/index' => 'posts/index',
'posts/view/<id:\d+>' => 'posts/view',    
'posts/<slug>' => 'posts/slug',

I get the following error

我收到以下错误

POST http://localhost:8888/posts/liked?id=56 500 (Internal Server Error)

1 个解决方案

#1


0  

There is not enough information so i am just assuming that your UrlManager config is like this.

没有足够的信息,所以我假设您的UrlManager配置是这样的。

    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName'=>false,
        'rules' => [
            'posts' => 'posts/index',
            'posts/index' => 'posts/index',
            'posts/view/<id:\d+>' => 'posts/view',
            'posts/<slug>' => 'posts/slug',
            ...

Where posts is PostsController and slug is actionSlug().

帖子是PostsController,slug是actionSlug()。

If your ajax request code is like below, it will work.

如果您的ajax请求代码如下所示,它将起作用。

        jQuery.ajax({
            url: '/posts/liked?id=56',
            type: 'POST',
            ...

I have tested this using the action function below in PostsController.

我使用PostsController中的动作函数对此进行了测试。

public function actionSlug() {
    $id = Yii::$app->request->get('id');
    echo json_encode($id);
}

#1


0  

There is not enough information so i am just assuming that your UrlManager config is like this.

没有足够的信息,所以我假设您的UrlManager配置是这样的。

    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName'=>false,
        'rules' => [
            'posts' => 'posts/index',
            'posts/index' => 'posts/index',
            'posts/view/<id:\d+>' => 'posts/view',
            'posts/<slug>' => 'posts/slug',
            ...

Where posts is PostsController and slug is actionSlug().

帖子是PostsController,slug是actionSlug()。

If your ajax request code is like below, it will work.

如果您的ajax请求代码如下所示,它将起作用。

        jQuery.ajax({
            url: '/posts/liked?id=56',
            type: 'POST',
            ...

I have tested this using the action function below in PostsController.

我使用PostsController中的动作函数对此进行了测试。

public function actionSlug() {
    $id = Yii::$app->request->get('id');
    echo json_encode($id);
}