繁体   English   中英

jQuery Ajax在一个表单中形成两个提交按钮

[英]jQuery Ajax form two submit button in one form

我有一种形式的2个按钮。 当我单击第一个或第二个按钮时,两个示例都写了一个警报,但是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>

animal-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;

?>

经过反复试验和错误后,如果您更改此行,我发现该脚本有效:

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

因为那样选择表单对象。

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

  • 不要在公共场合泄露密码
  • 不要让您的数据库用户在没有密码的情况下进行连接
  • 使用户具有严格的最低特权只是为了从PHP脚本连接到数据库(这称为最低特权原则)
  • 重命名您上传的文件

为了使文件上传正常工作:

  • 确保您对php.ini文件中的upload_tmp_dir指向的目录具有正确的权限
  • 您可能需要检查文件大小是否也未超出memmory_limit指令

祝好运,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM