doujiang1832 2011-02-15 13:28
浏览 110
已采纳

使用PHP的jQuery Ajax POST示例

I am trying to send data from a form to a database. Here is the form I am using:

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

The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.php)?

  • 写回答

13条回答 默认 最新

  • dsjbest2015 2014-03-25 21:25
    关注

    Basic usage of .ajax would look something like this:

    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);
        });
    
    });
    

    Note: Since jQuery 1.8, .success(), .error() and .complete() are deprecated in favor of .done(), .fail() and .always().

    Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).

    Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();

    PHP (that is, 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;
    

    Note: Always sanitize posted data, to prevent injections and other malicious code.

    You could also use the shorthand .post in place of .ajax in the above JavaScript code:

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

    Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?