javascript - 使用 PHP 的 jQuery Ajax POST 示例

标签 javascript jquery ajax post

我正在尝试将数据从表单发送到数据库。这是我正在使用的表格:

<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 准备好之后完成,因此您应该将其放在 $(document).ready() 中。处理程序(或使用 $() 简写)。

提示:您可以 chain回调处理程序如下所示:$.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;

注意:始终 sanitize posted data ,防止注入(inject)和其他恶意代码。

您还可以使用简写 .post代替上面 JavaScript 代码中的 .ajax:

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

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

关于javascript - 使用 PHP 的 jQuery Ajax POST 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45242335/

相关文章:

javascript - 从单个 DIV 创建 PDF

javascript - 无法使用 HTML5 PHP 和纯 ajax 上传图像

javascript - 如何更改一个按钮以在使用 jQuery 单击时切换当前/ future 事件?

javascript - jQuery 中如何检测当前元素?

javascript - 需要帮助将 jquery 转换为 javascript,添加到苹果的主屏幕

jquery - 函数适用于 Jquery 1.6.4 ,不适用于 Jquery 1.9.1

jquery - 如何仅在 jQuery 中显示 div 时运行函数?

javascript - jQuery,点击滚动窗口向下到div的顶部

javascript - 如何将 "this week"按钮变成下拉菜单?我究竟做错了什么?

Javascript,3秒后进行ajax调用