可以';t使用jsondecode打印ajax文章中的json


Can't print the json from ajax post using json_decode

我正在使用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($data as $key=>$value){
    print $value->ccyear;//now I can get at individual elements
}

但是任何带有破折号的值都会导致脚本失败。。。例如,如果名称是"mail firstname",PHP认为它是mail AND firstname。。。

问题是您的值在数据中嵌套了一个额外的级别。它们每个都有不同的钥匙,所以很难找到它们。如果使用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']等输入。