簡體   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