【发布时间】:2014-02-09 14:38:01
【问题描述】:
我是 Yii 和 ajax 的新手,我想从视图中读取模型的一些输入并使用 ajax 保存它。我在表单中使用了以下代码
<input type="button" name="save" value="save" onclick="saveFile()" id="profile-update" class="btn button-main" live="false">
而 saveFile() 是
function saveFile()
{
var data;
data = new FormData();
data.append('file', $('#UserProfile_profile_picture')[0].files[0]);
data.append('UserProfile', $('#profile-update-form').serialize());
$.ajax({
url: '<?php echo CHtml::normalizeUrl(array('user/profileupdate?rand=' . time())); ?>',
type:"POST",
data: data,
processData: false,
contentType: false,
success: function (data) {
$("#AjaxLoader1").hide();
if(data.status=="success"){
$("#formResult1").html("Profile settings changed successfully.");
$("#profile-update-form")[0].reset();
}
else{
$.each(data, function(key, val) {
$("#profile-update-form #"+key+"_em_").text(val);
$("#profile-update-form #"+key+"_em_").show();
});
}
},
beforeSend: function(){
$("#AjaxLoader1").show();
}
}
)
return false;
}
控制器中的代码是
$profile = UserProfile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
if (!$profile) {
$profile = new UserProfile;
$profile->create_time = time();
$profile->update_time = time();
}
if (isset($_POST['UserProfile'])) {
$profile->attributes = $_POST['UserProfile'];
$profile->profile_picture=$_FILES['file']['name'];
$images = CUploadedFile::getInstance($profile,'profile_picture');
// print_r($_POST);
// print_r($profile->phone);
// print_r($images);
// exit();
if (isset($images))
{
if(!is_dir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. 'quy'))
{
mkdir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. $profile->profile_picture);
// the default implementation makes it under 777 permission, which you could possibly change recursively before deployment, but here�s less of a headache in case you don�t
}
foreach ($images as $image => $pic)
{
echo $pic->name;if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/profilepic/'.$pic->name))
{
$profile->profile_picture = $pic->name;
}
}
}
$profile->user_id = Yii::app()->user->id;
$profile->update_time = time();
$valid = $profile->validate();
$error = CActiveForm::validate(array($profile));
if ($error == '[]') {
$profile->save(false);
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate(array($profile));
if ($error != '[]')
echo $error;
Yii::app()->end();
exit();
}
}
但这里只有 profile_picture 保存到数据库中,所有其他字段都没有改变。并且个人资料图片没有复制到文件夹中($images 为空白)请有人帮我解决这个问题。提前致谢
【问题讨论】:
-
您能告诉我们您的表单代码吗?
-
@Ali '$profile->attributes = $_POST['UserProfile'];'此代码不起作用
-
在打印 print_r($_POST) 时,它显示数组([UserProfile] => UserProfile%5Babout_me%5D=tyjtyjjy&UserProfile%5Bcity%5D=Delhiiii&UserProfile%5Bphone%5D=12111&UserProfile%5Bprofile_picture%5D=)像这样
标签: javascript php ajax yii