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

<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)?


当前回答

在你的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等等。

其他回答

如果你想用jQuery Ajax发送数据,那么就不需要表单标签和提交按钮

例子:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>

<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />

自从引入了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);

请核对一下。它是完整的Ajax请求代码。

$('#foo').submit(function(event) {
    // Get the form data
    // There are many ways to get this data using jQuery (you
    // can use the class or id also)
    var formData = $('#foo').serialize();
    var url = 'URL of the request';

    // Process the form.
    $.ajax({
        type        : 'POST',   // Define the type of HTTP verb we want to use
        url         : 'url/',   // The URL where we want to POST
        data        : formData, // Our data object
        dataType    : 'json',   // What type of data do we expect back.
        beforeSend : function() {

            // This will run before sending an Ajax request.
            // Do whatever activity you want, like show loaded.
        },
        success:function(response){
            var obj = eval(response);
            if(obj)
            {
                if(obj.error==0){
                    alert('success');
                }
                else{
                    alert('error');
                }
            }
        },
        complete : function() {
            // This will run after sending an Ajax complete
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert('error occured');
            // If any error occurs in request
        }
    });

    // Stop the form from submitting the normal way
    // and refreshing the page
    event.preventDefault();
});

我使用这个简单的一行代码多年没有问题(它需要jQuery):

<script src="http://malsup.github.com/jquery.form.js"></script> 
<script type="text/javascript">
    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

这里ap()表示Ajax页面,af()表示Ajax表单。在表单中,只需调用af()函数即可将表单发送到URL,并在所需的HTML元素上加载响应。

<form id="form_id">
    ...
    <input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>

我想分享一个详细的方法,如何张贴与PHP + Ajax以及错误抛出返回失败。

首先,创建两个文件,例如form.php和process.php。

我们将首先创建一个表单,然后使用jQuery .ajax()方法提交。其余的将在评论中解释。


form.php

<form method="post" name="postForm">
    <ul>
        <li>
            <label>Name</label>
            <input type="text" name="name" id="name" placeholder="Bruce Wayne">
            <span class="throw_error"></span>
            <span id="success"></span>
       </li>
   </ul>
   <input type="submit" value="Send" />
</form>

使用jQuery客户端验证表单并将数据传递给process.php。

$(document).ready(function() {
    $('form').submit(function(event) { //Trigger on form submit
        $('#name + .throw_error').empty(); //Clear the messages first
        $('#success').empty();

        //Validate fields if required using jQuery

        var postForm = { //Fetch form data
            'name'     : $('input[name=name]').val() //Store name fields value
        };

        $.ajax({ //Process the form using $.ajax()
            type      : 'POST', //Method type
            url       : 'process.php', //Your form processing file URL
            data      : postForm, //Forms name
            dataType  : 'json',
            success   : function(data) {
                            if (!data.success) { //If fails
                                if (data.errors.name) { //Returned if any error from process.php
                                    $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                }
                            }
                            else {
                                    $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                }
                            }
        });
        event.preventDefault(); //Prevent the default submit
    });
});

现在我们来看看process.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`

/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
    $errors['name'] = 'Name cannot be blank';
}

if (!empty($errors)) { //If errors in validation
    $form_data['success'] = false;
    $form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
    $form_data['success'] = true;
    $form_data['posted'] = 'Data Was Posted Successfully';
}

//Return the data back to form.php
echo json_encode($form_data);

项目文件可以从http://projects.decodingweb.com/simple_ajax_form.zip下载。