简体   繁体   English

如何使用.serialize()方法通过AJAX请求将表单值发送到PHP

[英]How to use the .serialize() method to send form values to PHP via an AJAX request

I'm using the .serialize() method to serialise my form's values and send them to my PHP script in an AJAX request. 我正在使用.serialize()方法来序列化我的表单的值,并在AJAX请求中将它们发送到我的PHP脚本。

My form: 我的表格:

<form name="myform" action="" method="post" class="form">
    <input type="text" name="one" value="" />
    <input type="text" name="two" value="" />
    <input type="text" name="three" value="" />
    <input type="submit" name="submit" value="Submit" />
</form>

My AJAX request: 我的AJAX请求:

$( '.form' ).on( 'submit', function( e ) {

$.ajax({
    type: 'POST',
    url: ajax_url,
    dataType: 'json',
    data: {
        'action': $action,
        'querystr': $( this ).serialize()
    }...

In my PHP script, I expected to be able to do something like this $one = $_REQUEST['one'] but when I do that the value of $one is null . 在我的PHP脚本中,我希望能够做这样的事情$one = $_REQUEST['one']但是当我这样做时, $one值为null

Why doesn't $_REQUEST['one'] contain the value of my form's input field? 为什么$_REQUEST['one']包含my form的输入字段的值?

On php end 在PHP结束

$params = array();
parse_str($_POST['querystr'], $params);
echo $params['one'];

It's all in your ajax call. 这都是你的ajax电话。 In the 'data' property , you declare the post fields that are sent to PHP. 在'data'属性中,您声明发送到PHP的post字段。 So in your code: 所以在你的代码中:

$.ajax({
type: 'POST',
url: ajax_url,
dataType: 'json',
data: {
    'action': $action,
    'querystr': $( this ).serialize()
}

You declare 你宣布

 $_POST['action']

, and ,和

 $_POST['querystr'].

Thats why $_POST['one'] is null - because it's not sent/defined etc. 这就是为什么$ _POST ['one']为空 - 因为它没有发送/定义等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM