AJAX 请求后未找到操作 [英] Action not found after AJAX request

查看:38
本文介绍了AJAX 请求后未找到操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提交之前,我想将请求发送到一个操作.但作为回报,我得到 404 not found.动作很明显.也在控制器的过滤器中得到它.JS:

Before for submitting I want to send the request to an action. But in return I get 404 not found. The action is obviously there. Also got it in the filters of the controller. JS:

$('#home-contact').on('beforeSubmit', function(){
                    $.ajax({
                        method: 'post',
                        url: '/site/send-contact',
                        data: new FormData($(this))[0],
                        success: function(data){
                            console.log(data)                          
                        }
                    })
                    return false
                })

控制器过滤器:

'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup', 'send-contact'],
                'rules' => [
                    [
                        'actions' => ['signup', 'send-contact'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],

还有这个动作:

public function actionSendContact()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $model = new Contact();
        if($model->load(Yii::$app->request->post()) && $model->save()){
            return $data['success'] = Yii::t('app', 'Successfully sent message.');
        }
        return $data['error'] = Yii::t('app', 'Something went wrong. Please try again.');
    }

这种情况发生在前端,如果这很重要的话.谢谢!

The scenario happens in the frontend if that matters somehow. Thank you!

推荐答案

不确定您所拥有的 404,因为请求中的 url 是否正确以及将为 ajax 生成的 url请求将类似于 http://example.com/site/send-contact 但前提是您使用的是 'enablePrettyUrl' =>对, 对于 urlManager 组件,否则它应该像 index.php?r=site/index 那样只能是 背后的原因404,更好的方法是从表单的action属性中获取url.

Not sure about the 404 you are having as the url in the request is correct and the url that would be generated for the ajax request will be like http://example.com/site/send-contact but only if you are using the 'enablePrettyUrl' => true, for the urlManager component, otherwise it should be like index.php?r=site/index that could only be the reason behind the 404, a better way is to get the url from the form action attribute.

除此之外,

您正在使用 new FormData() 发送带有请求的数据,例如

You are using the new FormData() to send the data with the request like

data: new FormData($(this))[0] 

这是不正确的,不会随请求发送任何 FormData,因为它会返回 undefined,您可以检查 console或者通过在操作 sendContact 中使用 print_r($_POST) 一旦你完成了 404,它应该是

which isn't correct and won't send any FormData with the request as it will return undefined, you can check the console or by using the print_r($_POST) inside the action sendContact once you are done with the 404, it should be

data: new FormData($(this)[0]),

您需要通过$(this)[0] 获取表单并传递给new FormData().

you need to get the form via $(this)[0] and pass to the new FormData().

但是这还不够,您必须将 contentTypeprocessData 设置为 false 才能正确提交FormData 否则你会在控制台中得到异常

But this is not enough you have to set the contentType and processData to be false to correctly submit the FormData or you will get the exception in console

未捕获的类型错误:非法调用

Uncaught TypeError: Illegal invocation

所以你的代码应该像

$('#contact-form').on('beforeSubmit', function(){
    let url=$(this).attr('action');
    let form=$(this)[0];
    let data=new FormData(form);

    $.ajax({
        method: 'post',
        url: url,
        data:data,
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false,
        success: function(data){
            console.log(data)                          
        }
    });
    return false;
})

编辑

注意:最重要的是,除非您有计划,否则您应该简单地使用 data:$(form).serialize() 而不是使用 new FormData()使用ajax上传文件和表单.

Note: Above all you should use data:$(form).serialize() simply rather than using new FormData() until unless you are planning to upload files along with the form using ajax.

这篇关于AJAX 请求后未找到操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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