服务器端的JQuery ajax序列化输入文本字段为空

时间:2014-04-24 07:25:31

标签: javascript php jquery ajax serialization

我的表单上有几个无线电字段和输入文本类型字段:

<input name="cbPerson" type="radio" value="1" checked/>Person1
<input name="cbPerson" type="radio" value="2"/>Person2
<input name="txtName" type="text" />

我正在以这种方式序列化我的表单:

$.ajax({
            type: 'post',           
            url: 'form-1-proc.php', 
            data: $('form').serialize(),
            success: function (data) {              
                 alert(data);
            },
            error: function () {
                alert('error');                 
            }
    });

我以这种方式获取服务器端的数据(form-1-proc.php):

$person = $_POST['cbPerson'];
$name = $_POST['txtName'];

变量$person具有预期值,但变量$name从不带值,并且始终为“0”。

此页面作为Joomla驱动的网站btw上的单独页面工作,页面本身位于网站的根目录,因此不会搞乱Joomla路由和东西。

您能否告诉我如何从输入文本字段中获取数据?两者都有name属性,如果我通过控制台输出serialize函数的值或使用javascript警告,它在客户端上保存一个值。

谢谢。

2 个答案:

答案 0 :(得分:1)

我无法复制这个问题。

<强> test.php的

<?php

if (count($_POST))
{
    $person = $_POST['cbPerson'];
    $name = $_POST['txtName'];
    exit("Person = $person | Name = $name");
}

?>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

function test()
{
    $.ajax({
    type: 'post',           
    url: 'test.php', 
    data: $('form').serialize(),
    success: function (data) {              
        alert(data);
    },
    error: function () {
        alert('error');                 
    }
    });
}

</script>

<form>
<input name="cbPerson" type="radio" value="1" checked/>Person1
<input name="cbPerson" type="radio" value="2"/>Person2
<input name="txtName" type="text" />
<input type="button" onclick="test();" value="Test">
</form>

enter image description here

答案 1 :(得分:0)

问题是当我试图获取服务器端的值时,我正在使用:

$name = $_POST['txtName'];
echo 'name:' + $name; 
die();

因此每当我试图获得它时,0的返回值。所以我把它改成了:

$name = $_POST['txtName'];
echo 'name'.$name;
die();

......得到了它。

JQuery序列化在我在Joomla网站上的隔离的php页面上运行良好。

感谢您的帮助。