php ajax post示例,带有PHP的jQuery Ajax POST示例

小编典典

的基本用法.ajax如下所示:

HTML:

A bar

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

提示:您可以 像这样链接回调处理程序:$.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之前的版本。

2020-04-22

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值