【问题标题】:Manipulate serialize ajax data to php操作序列化ajax数据到php
【发布时间】:2014-04-06 12:30:27
【问题描述】:

我正在努力在我的 php 代码中从 ajax 帖子中读取帖子数据。 我既不是 PHP 专家,也不是 Jquery 专家,几周前我就学会了。很抱歉,如果我还没有使用所有的术语。我从 ajax 序列化数据,因为我的表单中有更多字段。这里为了清楚起见,我只展示一个字段。 我正在尝试读取每个变量,例如在这种情况下的注释, 我只是尝试 print_r($_POST) 并且我得到了错误。 我看不到该怎么做,可能是转换或语法错误。 我将不胜感激任何见解

php 文件

public function ajaxSave($post_id)
    {

    print_r($_POST);    

}

jquery 脚本

$('body').on('click','#saveComment',function(e) {


            $("#comment-form").submit(function(e) {
                var postData = $(this).serialize();
                alert(postData);
                $.ajax( 
                {
                    url : "ajaxSave.php",
                    type: "POST",
                    data : postData,
                    dataType:"json",
                    success:function(data)
                        {
                            alert('success');
                        },
                    error: function(jqXHR, textStatus, errorThrown) 
                        {
                            alert("error");
                        }
                });
                e.preventDefault(); //STOP default action
                });
            $("#comment-form").submit(); 
        });

表格

<input id="Comment_comment" type="text" name="Comment[comment]" maxlength="140" size="60">

在 Firebug 中

在帖子标签中,我有

Comment[comment]    mycomment
Comment[post_id]    16

来源

Comment%5Bcomment%5D=mycomment&Comment%5Bpost_id%5D=16

在 HTML 标签中,我有

Array ( [Comment] => Array ( [comment] => for [post_id] => 16 ) ) 

【问题讨论】:

  • 你忘了引用url参数
  • 是的,谢谢,在我的代码中它被编码所以调用了 php 代码,我在重新转录时犯了一个错误@adeneo
  • 但错误当然仍然存在
  • 你遇到了什么错误?
  • 我讨厌名字、班级和 ID 中的大写字母。就像黑板上的钉子。给我们PHP错误

标签: php jquery ajax


【解决方案1】:

您期望 JSON 返回,但返回 $_POST 超全局的打印,这是一个 parseError。

删除 dataType 并将打印输出记录到控制台以查看它

$('body').on('click', '#saveComment', function (e) {
    e.preventDefault();
    $("#comment-form").trigger('submit');
});

$("#comment-form").submit(function(e) {
    e.preventDefault();
    var postData = $(this).serialize();
    alert(postData);
    $.ajax({
        url: "ajaxSave.php",
        type: "POST",
        data: postData,
        success: function (data) {
            console.log(data)
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("error");
        }
    });
});

并且不要在点击事件中绑定提交事件

【讨论】:

    【解决方案2】:

    print_r($_POST); 替换为echo json_encode($_POST);

    【讨论】:

      猜你喜欢
      • 2014-03-31
      • 2014-07-23
      • 2012-02-02
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      相关资源
      最近更新 更多