2017-07-15 77 views
1

我有一个形式的2个按钮。当我点击第一个或第二个按钮时,都会写入示例警报,但Ajax请求不会运行。我需要一张表格,因为我想上传图片。我不知道是什么问题。jQuery Ajax窗体两种提交按钮的一种形式

page.php文件

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>jQuery Ajax two submit in one form</title> 
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
</head> 
<body> 

<form id="animal-upload" method="post" enctype="multipart/form-data"> 

    <span>Name:</span> 
    <input type="text" name="animalname" id="animalname"> 

    <span>Image:</span> 
    <input type="file" name="imagefile" id="imagefile"> 

    <button type="submit" name="publish" id="publish">Publish</button> 
    <button type="submit" name="save" id="save">Save</button> 

</form> 

<script> 

$(document).ready(function() { 

$('#animal-upload').on('submit', function() { 

    return false; 

}); 

$('#publish').click(function() { 

    alert("Test"); 

}); 

$('#save').click(function(e) { 

    e.preventDefault(); 

    $.ajax({ 

     url: "animal-upload.php", 
     type: "POST", 
     data: new FormData(this), 
     contentType: false, 
     processData: false, 
     success: function(data) { 

      alert(data); 

     } 

    }); 

}); 

}); 

</script> 

</body> 
</html> 

试错动物upload.php的

<?php 

$connect = mysqli_connect("localhost", "root", "", "test"); 

mysqli_set_charset($connect,"utf8"); 

$status = ''; 

$animalname = $connect->real_escape_string($_POST["animalname"]); 

if ($_FILES['imagefile']['name'] != '') { 

    $extension = end(explode(".", $_FILES['imagefile']['name'])); 
    $allowed_type = array("jpg", "jpeg", "png"); 

    if (in_array($extension, $allowed_type)) { 

     $new_name = rand() . "." . $extension; 
     $path = "animals/" . $new_name; 

     if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $path)) { 

      mysqli_query($connect, "INSERT INTO animals (animalname,image) VALUES ('".$animalname."','".$path."')"); 

      $status = 'Successful!'; 

     } 

    } else { 

     $status = 'This is not image file!'; 

    } 

} else { 

    $status = 'Please select image!'; 

} 

echo $status; 

?> 
+0

尝试指定的数据类型。既然你没有指定,那只是猜测。 – Difster

+0

因为ajax请求成功运行,错误信息是什么 – user10089632

回答

0

后,我发现脚本工作,如果你改变这一行:

data: new FormData($("#animal-upload")[0]), 

因为这选择表单对象。

你可以考虑一些安全提示:

  • 不要在公共场所
  • 透露您的密码,不要让你的数据库连接的用户没有密码
  • 让用户有严格的最低权限只是从PHP脚本连接到您的数据库的目的(这就是所谓的最低权限原则)
  • 重命名您上传的文件

对于文件上传的工作:

  • 请确保您有对 upload_tmp_dir在php.ini文件
  • 指向的目录正确的权限,您可能需要检查您的文件大小不超过在memmory_limit指令太

好运,

+0

谢谢! :) :) – patesz

+0

@patesz,不客气 – user10089632