栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带有PHP的jQuery Ajax POST示例

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带有PHP的jQuery Ajax POST示例

的基本用法

.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 requestvar 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()
处理程序中(或使用
$()
简写形式)。

提示:您可以 像这样链接回调处理程序:

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

注意:始终 清理发布的数据,以防止注入和其他恶意代码。

你也可以使用速记

.post
代替
.ajax
在上面的Javascript代码:

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/377373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号