Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

php - 带有PHP的jQuery Ajax POST示例(jQuery Ajax POST example with PHP)

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

(使用jQuery和Ajax ,是否可以捕获表单的所有数据并将其提交给PHP脚本(例如form.php )?)

  ask by Thew translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Basic usage of .ajax would look something like this:

(.ajax基本用法如下所示:)

HTML:

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

(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() .

(注:由于jQuery的1.8, .success() .error().complete()赞成已被弃用.done() .fail().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).

(注意:请记住,上面的代码段必须在DOM准备就绪后完成,因此您应将其放在$(document).ready()处理函数中(或使用$()简写形式)。)

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

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

PHP (that is, form.php):

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

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:

(您还可以在上述JavaScript代码中使用简写.post代替.ajax :)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...