PHP,Jquery ajax没有将表单作为可识别的$ _POST传递

时间:2013-01-24 06:32:09

标签: php jquery ajax

使用 .ajax()

时,jQuery似乎没有传递表单变量或http POST操作

执行 var_dump($ _POST); 会产生一个空数组。

连连呢?我做错了什么......这是一个简单的概念 - 有人esle发布了一个类似的Q,但没有人回复,他的解决方案是在表单中添加一个id,我已经有了,所以它不能解决我的问题。

目前我正在查看firebug中的返回页面内容 - 我还没有做任何事情,因为我无法将数据提供给服务器......(首先要做的事情)。

我的HTML

<script type="text/javascript">
$( document ).ready( function(){
    $( "#myform" ).submit( function () {
        $.ajax({
            type: "POST",
            dataType: "html",
            cache: false,
            url: "x.php",
            success: function( data ){              
                //...tell user there was success...
            },
            error: function( data ){
                //...tell user thre was a problem...
            }
        });
        return false;
    });     
});
</script>

<form name="myform" id="myform" action="" method="POST">
    <label for="name" id="name_label">x: </label>
    <input type="text" name="x" id="x" size="30" value=""/> 
    <input type="submit" name="submit" value="Submit"> 
</form>
<div id="results"><div>

这是(x.php)PHP代码 - 非常简单的概念证明......

<?php
var_dump( $_GET );
var_dump( $_POST );
var_dump( $_REQUEST );
?>

响应看起来像这样

array(0) {}
array(0) {}
array(1) {
  ["PHPSESSID"]=>
  string(26) "e1j18j..."
}

3 个答案:

答案 0 :(得分:5)

你没有在ajax调用中传递任何帖子data,请尝试

    $.ajax({
        type: "POST",
        dataType: "html",
        cache: false,
        url: "x.php",
        data: $(this).serialize(),
        success: function( data ){              
            //...tell user there was success...
        },
        error: function( data ){
            //...tell user thre was a problem...
        }
    });

答案 1 :(得分:1)

您需要序列化表单:

    $.ajax({
        type: "POST",
        data: $(this).serialize(),
        cache: false,
        url: "x.php",
        success: function( data ){              
            //...tell user there was success...
        },
        error: function( data ){
            //...tell user thre was a problem...
        }
    });

如果没有data,则不会发送任何有关POST请求的内容。

答案 2 :(得分:0)

你可以这样做

$(document).ready(function(){
   $( "#myform" ).submit( function () {
       $.ajax({
         type:'POST',
         data:'xname='+$("#x").val(),
         url:'SOMETHING.php',
         success:function(data){
           //Do something with the returned data
         }
       });
   });
});

在php文件中

echo $_POSST['xname'];

希望这有帮助