【问题标题】:Can't print the json from ajax post using json_decode无法使用 json_decode 从 ajax 帖子打印 json
【发布时间】:2014-10-25 12:43:12
【问题描述】:

我正在使用 ajax 将数据发布到 php 脚本以完成工作...基本上,我采用所有表单变量,并创建 json...然后将此 json 发送到控制器脚本:

function createJSON() {
                 jsonObj = [];
                 $("input[class=form-control]").each(function() {
                    var id = $(this).attr("id");
                    var value = $(this).val();
                    item = {}
                    item [id] = value;
                    jsonObj.push(item);
                 });

             jsonData = JSON.stringify(jsonObj);

             var request = $.ajax({
             url: "../../../../ajax/signupController.php",
             type: "POST",
             data: jsonData,
             dataType: "html"
            });

            request.done(function( msg ) {
            console.log(msg);
            });

            request.fail(function( jqXHR, textStatus ) {
                alert( "Request failed: " + textStatus );
            });

            }

我的代码很好地进入了 php 脚本,当我在 php 中使用“print_r”打印输出时,我得到了这个:

Array
(
[0] => stdClass Object
    (
        [mail-firstname] => FName
    )

[1] => stdClass Object
    (
        [mail-lastname] => Lname
    )
)

我的问题是,我无法获取元素...我已经尝试过:

$data = json_decode(file_get_contents('php://input'));  
foreach ($data as $key => $value) { 
print "<p>$key | $value</p>";
}

但我无法获取数组元素...我收到一个错误...在解码文件内容后访问数组我缺少什么?

谢谢。

更新:

修改后的foreach:

foreach($data as $key=>$value){
    print $value->ccyear;//now I can get at individual elements
}

但是任何有破折号的值都会导致脚本失败...例如,如果名称是“mail-firstname”,PHP 认为它是邮件和名字...

【问题讨论】:

  • json_decode(,true) :)

标签: php jquery ajax json


【解决方案1】:

问题是您的值嵌套在数据中的额外级别。而且他们每个人都有不同的钥匙,所以很难拿到他们。最好使用id作为顶级数组的键,而不是嵌套它们:

jsonObj = {};
$("input[class=form-control]").each(function() {
    var id = this.id
    var value = this.value;
    jsonObj[id] = value;
 });

然后你应该将你的 PHP 更改为使用 json_decode() 的第二个参数,这样你就会得到一个关联数组而不是 stdClass 对象:

$data = json_decode(file_get_contents('php://input', true));

我不太确定为什么需要发送 JSON。为什么不直接使用:

data: jsonObj;

然后您可以以$_POST['mail-firstname'] 等身份访问输入。

【讨论】:

  • 嗨 Barmar,我没有意识到您可以创建一个数组,然后将其作为 POST vals 发送...我认为您必须将数据格式化为 json 才能发送...我会尝试你的建议。感谢您抽出宝贵时间。
  • 我无法让帖子工作,但我能够使用您删除数据嵌套的建议......然后我能够使用以下命令访问每个值:“print $data ->{'mail-firstname'};"非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 2023-04-03
  • 2017-01-03
  • 1970-01-01
相关资源
最近更新 更多