我对ajax表单有疑问。所以,你可以看到我的以下ajax代码有data-id
。我在.pmsc
div中获得此ID。但是当我按 #upmsc 上传图片时,我没有收到任何错误,只是从chrome开发者控制台获取此结果,没有上传,没有在数据库中插入图像名称。我在这里做错了什么。
然后ajax提交表单就是这个
$('body').on('change', '#upmsc', function(e) {
e.preventDefault();
var id = $(".pmsc").attr("data-id");
var data = 'id=' + id;
$("#musicform").ajaxForm({
type: "POST",
data: data,
cache: false,
target: '.appended',
beforeSubmit: function() {
// Do Something
},
success: function(response) {
// Do Something
$(".showecho").html(response);
},
error: function() {}
}).submit();
});
我的html表单是这样的:
<form id="cfrm" class="options-form" method="post" enctype="multipart/form-data" action="'.$base_url.'upload.php">
<label class="mcup" for="upcmsc"></label>
<input type="file" name="musicCover" id="upcmsc" />
</form>
<div class="pmsc" id="56">
</div>
和PHP代码就是这个
<?php
include_once 'inc/inc.php';
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['id'])) {
$id = mysqli_real_escape_string($db, $_POST['id']);
$name = $_FILES['musicCover']['name'];
$size = $_FILES['musicCover']['size'];
if(strlen($name)) {
$ext = getExtension($name);
if(in_array($ext,$valid_formats)) {
if($size<(50024*50024)) {
$actual_image_name = time().$uid.".".$ext;
$tmp = $_FILES['musicCover']['tmp_name'];
if(move_uploaded_file($tmp, $mcoverpath.$actual_image_name)) {
$data=$HuHu->Music_Cover_Image_Upload($id,$actual_image_name);
if($data){
echo '<img class="cover covermsc" src="'.$base_url.$mcoverpath.$actual_image_name.'">';
}
} else {
echo "Fail upload folder with read access.";
}
} else
echo "Image file size max 1 MB";
} else
echo "Invalid file format.";
} else
echo "Please select image..!";
exit;
}
?>
答案 0 :(得分:1)
var data = 'id=' + id;
$("#musicform").ajaxForm({
type: "POST",
data: data,
将附加数据设置为字符串,同时应将其作为对象。那么你的PHP代码检查就失败了。所以试试这个:
var data = {id: id};
在PHP代码括号中发现了一些问题,试试这个:
<?php
include_once 'inc/inc.php';
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['id'])) {
$id = mysqli_real_escape_string($db, $_POST['id']);
$name = $_FILES['musicCover']['name'];
$size = $_FILES['musicCover']['size'];
if(strlen($name)) {
$ext = getExtension($name);
if(in_array($ext,$valid_formats)) {
if($size<(50024*50024)) {
$actual_image_name = time().$uid.".".$ext;
$tmp = $_FILES['musicCover']['tmp_name'];
if(move_uploaded_file($tmp, $mcoverpath.$actual_image_name)) {
$data=$HuHu->Music_Cover_Image_Upload($id,$actual_image_name);
if($newdata){
echo '<img class="cover covermsc" src="'.$base_url.$mcoverpath.$actual_image_name.'">';
}
} else {
echo "Fail upload folder with read access.";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format.";
}
} else {
echo "Please select image..!";
exit;
}
} else {
echo '1';
}
?>