我有一个文本类型的输入文本框和一个文件类型的输入文本框。我想在单击按钮时通过ajax将这些值发送到php文件。一切似乎都很好,但由于某种疯狂的原因,如果未在php文件中标识该图像。 请帮助,没有想法。我的代码如下。
==========当id = Saved的按钮被点击时的JavaScript代码====
$("#saved").on('click',function(){
$("#itemform").submit(function(e){
e.preventDefault();
});
var item_desc =document.getElementById("item_desc").value;
var item_price_type =document.getElementById("item_price_type").value;
var item_regular_price =document.getElementById("item_regular_price").value;
var item_type =document.getElementById("item_type").value;
var item_cat =document.getElementById("item_cat").value;
var taxablee =document.getElementById("taxablee").value;
var item_price_tax =document.getElementById("item_price_tax").value;
var item_offer_price=document.getElementById("item_offer_price").value;
var offer_start =document.getElementById("offer_start").value;
var offer_end =document.getElementById("offer_end").value;
var file =document.getElementById('file').value;
var price_tax="";
var formdata = new FormData();
formdata.append('file',file);
formdata.append('item_desc',item_desc);
formdata.append('item_price_type',item_price_type);
formdata.append('item_regular_price',item_regular_price);
formdata.append('item_type',item_type);
formdata.append('item_cat',item_cat);
formdata.append('taxablee',taxablee);
formdata.append('price_tax',price_tax);
formdata.append('item_offer_price',item_offer_price);
formdata.append('offer_start',offer_start);
formdata.append('offer_end',offer_end);
});
============ php文件将数据插入数据库===========
$item_desc =$_POST['item_desc'];
$item_price_type=$_POST['item_price_type'];
$item_regular_price=$_POST['item_regular_price'];
$item_type=$_POST['item_type'];
$item_cat=$_POST['item_cat'];
$taxablee=$_POST['taxablee'];
$price_tax=$_POST['price_tax'];
$item_offer_price=$_POST['item_offer_price'];
$offer_start=$_POST['offer_start'];
$offer_end=$_POST['offer_end'];
$item_image = $_FILES['file']['name'];
$folder = "../menu_images/";
$pics =time().$item_image;
//$sq="// this is my insert statment";
//$sq_insert =$conn->prepare($sq);
//$sq_insert->execute(array(//these are my array values for the insert
statment));
move_uploaded_file($_FILES["file"]["tmp_name"], $folder.$pics);
答案 0 :(得分:0)
为什么不只使用html表单提交数据,也不需要使用javascript。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
答案 1 :(得分:0)
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
});