我定义一个实体 无法获取POST过来的表单数据,代码如下:
1、Action
namespace app\controllers;
use app\models\FormModel;
use Yii;
use yii\web\Controller;
use yii\web\Request;
use yii\web\Response;
class FormController extends Controller {
public $enableCsrfValidation = false;
public function actionIndex()
{
$this->layout=false;
return $this->render("index",[]);
}
public function actionPost()
{
$model=new FormModel();
$model->load($_POST);
$model->attributes=$_POST;
echo json_encode($model->name);
}
}
2、Model
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class FormModel extends ActiveRecord {
public static function tableName()
{
return 'formmodel';
}
public function rules()
{
return [
[['name', 'name'], 'required'],
['id', 'id'],
];
}
}
3、视图
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width"/>
<title>用户登录</title>
<script src="/static/js/vendor/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
<form id="form1" method="post" action="/form/post">
id:<input type="text" name="id"/><br/>
name:<input type="text" name="name"/><br/>
<input type="button" id="btn" value="sumbit"/>
</form>
</div>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$.ajax({
type: 'POST',
url: "/form/post",
data: $("#form1").serialize(),
success: function (data) {
},
dataType: "html"
});
});
});
</script>
</body>
</html>
4、视图对应表SQL
CREATE TABLE `formmodel` (
`id` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
错误:
Exception 'ReflectionException' with message 'Class id does not exist'
in E:\Soft\PHP\yii\yii-basic-app-2.0.3\basic\vendor\yiisoft\yii2\di\Container.php:415
Stack trace:
表单名称命名不符合yii规范,
改为
url: "/form/post",
有错误
1.检查点击是否做ajax提交了
2.后台试着输出POST过去的数据,看看是不是你php代码有问题
$model=new FormModel();这个有东西么?