JSON PHP解码无法正常工作

时间:2014-04-02 13:27:53

标签: php json

我见过很多例子,但无论出于何种原因,似乎没有一个例子适合我。

我从应用程序通过ajax发送以下内容到php文件。这是它发送时的样子:



    obj:{"ClientData":
    [{
        "firstName":"Master",
        "lastName":"Tester",
        "email":"me@me.com",
        "dob":"1973-01-22",
        "age":"51",
    }],
    "HealthData":
    [
        "condition : Prone to Fainting / Dizziness",
        "condition : Allergic Response to Plasters",
    ],
    "someData":
    [{
        "firstName":"Male",
        "lastName":"checking",
    }]
    }

Here is how it looks in debugger

代码原样:

{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me@me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}

这是一个很长的行到一个php文件,这里是代码:

<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
//var_dump($_POST['obj']);

$Ojb = json_decode($_POST['obj'],true);

$clientData = $Ojb['ClientData'];
$healthData = $Ojb->HealthData;
$someData = $Ojb->someData;

print_r($clientData['firstName']);    
?>

无论我尝试过什么,我都看不到任何信息,我甚至都没有收到错误,只是空白!请有人指出我正确的方向。

谢谢:)

更新

以下是创建对象的代码:

ClientObject = {

        ClientData : [
            {
                firstName : localStorage.getItem('cfn'),
                lastName : localStorage.getItem('cln'),
                email : localStorage.getItem('cem'),
                dob : localStorage.getItem('cdo'),
                age : localStorage.getItem('cag'),
                pierceType : localStorage.getItem('cpt'),
                street : localStorage.getItem('cst'),
                city : localStorage.getItem('cci'),
                county : localStorage.getItem('cco'),
                postcode : localStorage.getItem('cpc')
            }
        ],

        HealthData : health,

        PiercerData : [
        {
                firstName : localStorage.getItem('pfn'),
                lastName : localStorage.getItem('pln'),
                pierceDate : localStorage.getItem('pda'),
                jewelleryType : localStorage.getItem('pjt'),
                jewelleryDesign : localStorage.getItem('pjd'),
                jewellerySize : localStorage.getItem('pjs'),
                idChecked: localStorage.getItem('pid'),
                medicalChecked: localStorage.getItem('pmh'),
                notes: localStorage.getItem('poi')
        }
        ]

    };

以下是它的发送方式:

function senddata() {
    $.ajax({
        url: 'http://domain.com/app.php',
        type: 'POST',
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        dataType: 'jsonp',              
        data: 'obj='+JSON.stringify(ClientObject),

        success : function(res) {
            console.log(res);

        },
        error: function(err) {

        }
    });
}

2 个答案:

答案 0 :(得分:3)

$Ojb = json_decode($_POST['obj'],true);

使它成为数组所以你需要使用数组索引而不是对象

来获取它们

<强> UPDATE1

在此处更新如何完成

$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me@me.com","‌​dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["‌​condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDat‌​e":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"‌​Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}' ;

$obj = json_decode($str,true);

echo $obj["ClientData"][0]["firstName"];

您可以获得上述其他元素

<强> UPDATE2

您将数据作为JSONP发送,这将使请求为

?callback=jQuery17108448240196903967_1396448041102&{"ClientData"

现在您还要添加data: 'obj='这是不正确的。

你可以简单地发送为json而不是jsonp

并在php文件上,你可以做

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

答案 1 :(得分:3)

有一些事情会导致问题:

  1. 为什么dataType: 'jsonp'?如果您不打算使用jsonp,请不要指示jQuery执行此操作。请参阅文档:https://api.jquery.com/jQuery.ajax/

      

    “jsonp”:使用JSONP加载JSON块。添加一个额外的   “?回调=?”到URL的末尾以指定回调。禁用   通过将查询字符串参数“_ = [TIMESTAMP]”附加到缓存来缓存   URL除非cache选项设置为true。

  2. 'obj='+JSON.stringify(ClientObject),这将保证无效的json。

  3. 作为参考,请看一下这个问题:jQuery ajax, how to send JSON instead of QueryString关于如何使用jquery发送json。


    尽管如此,请尝试以下方法:

    function senddata() {
      $.ajax({
        url: 'app.php',
        type: 'POST',
        crossDomain: true,
        contentType: 'application/json; charset=utf-8"',
        data: JSON.stringify(ClientObject),
        success : function(res) {
          console.log(res);
        },
        error: function(err) {
        }
      });
    }
    

    并在app.php中使用

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

    获取数据。使用它像:

    var_dump($input->ClientData[0]->firstName); // => string(6) "Master"