![](/img/trans.png)
[英]how to use $.post() to send request and add data to database in yii2
[英]Failed to send Javascript data to action by POST method with Yii2
我遇到了问题,我通过AJAX从Javascript连接到我的操作,并通过POST发送数据。 我声明URL为“ / controller / action”,但未连接到该动作,而AJAX给我“ parsererror”。 奇怪的是,我做了同样的事,但是得到了平等的行动,但没有给我错误,我做得很好
我的JS文件
function save_account(){
$.ajax({
url: '/user/save-account',
type: 'POST',
dataType: 'json',
data: {
'id_user': xxx,
'email': xxx,
'name': xxx,
'type': xxx
},
contentType: 'application/x-www-form-urlencoded;charset=ISO-8859-15',
async: false,
success: function (response) {
},
error : function (request, error) {
console.log(error);
}
});
}
我在控制器中的动作
public function actionSaveAccount(){
$model= new \frontend\models\ProfileForm();
if (Yii::$app->request->isAjax) {
if ($model->load(Yii::$app->request->post())){
if($profile === $model->saveProfile()){
// SAVED
}else{
// ERROR SAVED
}
}
}
}
我的网址设置
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
],
],
您正在使用连字符( -
)向URL发送请求,而用于路由的正则表达式是w
字符,根据regex101 ,该字符用于以下内容:
\\ W
匹配任何字母,数字或下划线。 等效于[a-zA-Z0-9_]
将URL更改为save_account,它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.