当按下使用ajax

时间:2017-02-21 06:40:21

标签: javascript php jquery ajax

我想在没有页面加载效果的情况下按下回车键上传图像和文本字段值。 它显示一条错误消息 TypeError:FormData.constructor的参数1没有实现HTMLFormElement接口。

以下是我的代码可以帮助https://jsfiddle.net/rijo/sx73rwe5/

php code

<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 10000000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

1 个答案:

答案 0 :(得分:3)

根据定义:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

  

构造包含现有数据的FormData对象   <form>,在创建FormData对象时指定该表单元素。

您正在将this传递给formData,这是您案例keypress$('#test_name')事件的目标obj。您需要传递表单DOM元素:

new FormData($("#uploadimage")[0]);