【问题标题】:PHP, Jquery ajax not passing form as recognizable $_POSTPHP,Jquery ajax 未将表单传递为可识别的 $_POST
【发布时间】:2013-01-24 06:32:08
【问题描述】:

使用 .ajax()

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

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

建议?我做错了什么......这是一个简单的概念 - 有人 esle 发布了类似的问题,但没有人回复,他的解决方案是在表单中添加一个 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..."
}

【问题讨论】:

  • 表单“myform”,文本字段“x”....
  • 最好直接使用$.post()。

标签: php jquery ajax


【解决方案1】:

你没有在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...
        }
    });

【讨论】:

    【解决方案2】:

    需要对表单进行序列化:

        $.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 请求不会发送任何内容。

    【讨论】:

      【解决方案3】:

      你可以这样做

      $(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'];
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2012-02-13
        • 2023-03-28
        • 2020-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-16
        • 1970-01-01
        相关资源
        最近更新 更多