jquery ajax php post,与PHP的jQuery Ajax POST例子

我正在尝试从窗体发送数据到数据库。这是我正在使用的窗体:

A bar

典型的方法是提交表单,但这会导致浏览器重定向。使用 jQuery 和 Ajax,是否有可能捕获所有表单的数据并将其提交给 PHP 脚本(例如,form.php)?

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

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

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

$.post('/form.php', serializedData, function(response) {

// Log the response to the console

console.log("Response: "+response);

});

注意:上面的 JavaScript 代码是用于 jQuery 1.8 和更高版本的,但是它应该可以在之前的版本中使用 jQuery 1.5。

要使用 jQuery 制作 ajax 请求,你可以通过下面的代码来做到这一点

HTML:

A bar

JavaScript 的:

方法 1

/* Get from elements values */

var values = $(this).serialize();

$.ajax({

url: "test.php",

type: "post",

data: values ,

success: function (response) {

// you will get response from your php page (what you echo or print)

},

error: function(jqXHR, textStatus, errorThrown) {

console.log(textStatus, errorThrown);

}

});

方法 2

/* Attach a submit handler to the form */

$("#foo").submit(function(event) {

var ajaxRequest;

/* Stop form from submitting normally */

event.preventDefault();

/* Clear result div*/

$("#result").html('');

/* Get from elements values */

var values = $(this).serialize();

/* Send the data using post and put the results in a div */

/* I am not aborting previous request because It's an asynchronous request, meaning

Once it's sent it's out there. but in case you want to abort it you can do it by

abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */

ajaxRequest= $.ajax({

url: "test.php",

type: "post",

data: values

});

/* request cab be abort by ajaxRequest.abort() */

ajaxRequest.done(function (response, textStatus, jqXHR){

// show successfully for submit message

$("#result").html('Submitted successfully');

});

/* On failure of request this function will be called */

ajaxRequest.fail(function (){

// show error

$("#result").html('There is error while submit');

});

.success(),.error()和.complete()回调从 jQuery

1.8 开始已弃用。要准备代码以便最终删除它们,请改为使用.done(),.fail()和.always()。

MDN: abort()。如果请求已经发送,则此方法将中止请求。

所以我们现在已经成功发送 ajax 请求来抓取数据到服务器。

PHP

当我们在 ajax 调用(type: "post")中发出 POST 请求时,我们现在可以使用$_REQUEST或$_POST

$bar = $_POST['bar']

你也可以通过简单的方式看到你在 POST 请求中得到了什么,顺便说一句,确保 $ _POST 被设置为其他方式,你会得到错误。

var_dump($_POST);

// or

print_r($_POST);

而且你正在向数据库插入值,确保你正在敏感或转义所有的请求(天气你做 GET 或 POST)之前进行查询,最好将使用预处理语句。

如果你想返回任何数据返回页面,你可以通过如下回显数据来做到这一点。

// 1. Without JSON

echo "hello this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below

echo json_encode(array('returned_val' => 'yoho'));

比你可以得到它

ajaxRequest.done(function (response){

alert(response);

});

有几个速记方法你可以使用下面的代码它做同样的工作。

var ajaxRequest= $.post( "test.php",values, function(data) {

alert( data );

})

.fail(function() {

alert( "error" );

})

.always(function() {

alert( "finished" );

});

未经作者同意,本文严禁转载,违者必究!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值