我试图将数据从表单发送到数据库。这是我使用的形式:

<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

典型的方法是提交表单,但这会导致浏览器重定向。使用jQuery和Ajax,是否有可能捕获所有表单的数据并将其提交给PHP脚本(例如,form. PHP)?


当前回答

ajax的基本用法是这样的:

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

jQuery:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});

注意:从jQuery 1.8开始,.success(), .error()和.complete()已被弃用,取而代之的是.done(), .fail()和.always()。

注意:请记住,上面的代码段必须在DOM ready之后完成,因此应该将其放在$(document).ready()处理程序中(或使用$()简写)。

提示:你可以像这样链接回调处理程序:$.ajax().done().fail().always();

PHP(即form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

注意:总是消毒发布的数据,以防止注入和其他恶意代码。

你也可以在上面的JavaScript代码中使用。post来代替。ajax:

$.post('/form.php', serializedData, function(response) {
    // Log the response to the console
    console.log("Response: "+response);
});

注意:上面的JavaScript代码适用于jQuery 1.8及更高版本,但它应该适用于jQuery 1.5之前的版本。

其他回答

自从引入了Fetch API,就没有理由再用jQuery Ajax或xmlhttprequest来实现了。要POST表单数据到php脚本在香草JavaScript你可以做以下:

异步函数postData() { 尝试{ Const res = await fetch('../php/contact.php', { 方法:“文章”, new FormData(document.getElementById('form')) }) if (!res.ok)抛出新的错误('网络响应不正常'); } catch (err) { console.log (err) } } <form id="form" action="javascript:postData()" > <input id="name" name="name" placeholder=" name" type="text" required> <input type="submit" value=" submit" > > < /形式

下面是一个非常基本的php脚本示例,它获取数据并发送电子邮件:

<?php
    header('Content-type: text/html; charset=utf-8');

    if (isset($_POST['name'])) {
        $name = $_POST['name'];
    }

    $to = "test@example.com";
    $subject = "New name submitted";
    $body = "You received the following name: $name";
    
    mail($to, $subject, $body);

在你的php文件中输入:

$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";

在你的js文件中发送一个带有数据对象的ajax

var data = { 
    bar : 'bar value',
    time: calculatedTimeStamp,
    hash: calculatedHash,
    uid: userID,
    sid: sessionID,
    iid: itemID
};

$.ajax({
    method: 'POST',
    crossDomain: true,
    dataType: 'json',
    crossOrigin: true,
    async: true,
    contentType: 'application/json',
    data: data,
    headers: {
        'Access-Control-Allow-Methods': '*',
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
        "Access-Control-Allow-Origin": "*",
        "Control-Allow-Origin": "*",
        "cache-control": "no-cache",
        'Content-Type': 'application/json'
    },
    url: 'https://yoururl.com/somephpfile.php',
    success: function(response){
        console.log("Respond was: ", response);
    },
    error: function (request, status, error) {
        console.log("There was an error: ", request.responseText);
    }
  })

或者保持表单提交的原样。只有当您希望发送带有计算附加内容的修改过的请求,而不仅仅是一些由客户机输入的表单数据时,才需要这种方法。例如哈希、时间戳、用户id、会话id等等。

HTML:

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }

这是使用ajax在HTML中填充选择选项标签的代码,而XMLHttpRequest和API是用PHP和PDO编写的

conn.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

category.php

<?php
 include 'conn.php';
try {
    $data = json_decode(file_get_contents("php://input"));
    $stmt = $conn->prepare("SELECT *  FROM events ");
    http_response_code(200);
    $stmt->execute();
    
    header('Content-Type: application/json');

    $arr=[];
    while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
        array_push($arr,$value);
    }
    echo json_encode($arr);
   
  } catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
  }

script.js

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        data = JSON.parse(this.responseText);

        for (let i in data) {


            $("#cars").append(
                '<option value="' + data[i].category + '">' + data[i].category + '</option>'

            )
        }
    }
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();

index . html


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <title>Document</title>
</head>

<body>
    <label for="cars">Choose a Category:</label>

    <select name="option" id="option">
        
    </select>
    
    <script src="script.js"></script>
</body>

</html>

纯JS

在纯JS中,这要简单得多

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}

foo.onsubmit = e=> { e.preventDefault(); fetch(foo.action,{method:'post', body: new FormData(foo)}); } <form name=“foo” action=“form.php” method=“POST” id=“foo”> <label for=“bar”>A bar</label> <输入 id=“bar” 名称=“bar” 类型=“文本” 值=“” /> <输入类型=“提交”值=“发送” /> </form>