2014-04-02 1 views
0

많은 사례를 보았습니다. 그러나 어떤 이유로 든 아무 것도 저에게 효과가없는 것 같습니다.JSON PHP 디코드가 작동하지 않습니다.

다음과 같이 ajax를 통해 PHP 파일로 전송됩니다.

 


    obj:{"ClientData": 
    [{ 
     "firstName":"Master", 
     "lastName":"Tester", 
     "email":"[email protected]", 
     "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

코드와 같이 : 이것은 그하여 전송이 때 모습입니다 이것은 PHP 파일에 하나의 긴 줄에 제공

{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"[email protected]","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 
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']);  
?> 

아무리 노력해도 정보를 볼 수 없으며 오류가 발생하지 않습니다. 그냥 비어 있습니다! 누군가 제게 올바른 방향으로 나를 가르쳐 줄 수 있습니까?

감사합니다 :)

UPDATE 여기

객체 생성 코드입니다 :

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) { 

     } 
    }); 
} 
+1

이것은 저에게 유효한 json처럼 보이지 않습니다. –

+0

var_dump ($ Ojb)하면 어떻게됩니까? null을 얻으면 json은 유효하지 않습니다. 여전히 빈 페이지가 나타나면 PHP 오류가 발생합니다. json 모듈을 서버에 설치하지 않았을 수 있습니다. – quano

+0

가능한 복제 http://stackoverflow.com/questions/16828647/php-json-decode-does-not-work –

답변

2

문제를 일으킬 것 몇 가지가 있습니다으로 PHP 파일에 당신이 할 수있는 JSONP JSON으로 보낼 수 있습니다

  1. dataType: 'jsonp'? jsonp를 사용하지 않으려는 경우 jQuery에 지시하지 마십시오. 문서 참조 : https://api.jquery.com/jQuery.ajax/

    "jsonp": JSONP를 사용하여 JSON 블록에로드합니다.추가로 을 추가합니까? "callback =?" URL의 끝에 추가하여 콜백을 지정하십시오. 캐시 옵션이 true로 설정되어 있지 않으면 URL에 쿼리 문자열 매개 변수 "_ = [TIMESTAMP]"를 추가하여 캐싱을 사용하지 않도록 설정합니다.

  2. 'obj='+JSON.stringify(ClientObject), 이것은 잘못된 json을 보장합니다.

참고로, jquery와 함께 json을 보내는 방법에 대한 자세한 내용은 jQuery ajax, how to send JSON instead of QueryString을 참조하십시오. 말했다


다음을 수행하십시오

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) { 
    } 
    }); 
} 

및 사용

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

app.php에서의 데이터를 얻을 수 있습니다. 다음과 같이 사용하십시오 :

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

예 정확히 문제가 있습니다 !! –

+0

@Yoshi 위의 내용을 고맙게 생각하고 위에 적어 놓은 것을 인쇄했습니다. jsonp의 이유는 접근 제어 오류가 발생하는 이유입니다. 다시 귀하의 코드와 함께있어,하지만 난 헤더 및 그 작업을 변경 –

3
$Ojb = json_decode($_POST['obj'],true); 
u는 그들이 당신과 같은 다른 요소를 얻을 수는

$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"[email protected]","‌​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"]; 

을 수행하는 방법은 여기 업데이트를 갱신 1

객체

대신 배열 인덱스를 사용하는 데 필요한, 그래서

는 배열한다 UPDATE2

당신은 JSONP로 데이터를 전송하는

이것은

?callback=jQuery17108448240196903967_1396448041102&{"ClientData" 

이제 당신은 또한 정확하지 않은 data: 'obj='를 추가로 요청을 만들 것입니다.

당신은 간단하지

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

그래서 나는 다음과 같은 것을 사용할 것이다 :'$ Ojb = (array) json_decode ($ _ POST [ 'obj'], true);'? –

+0

아니요 (배열)을 사용할 필요가 없습니다. 유효한 json처럼 보이지 않습니다. 수신 한 json 문자열을 게시하십시오. –

+0

Okay @ Yoshi 그러나 실제 데이터는 이미 위에 있습니다. 그러나 그것을 청소하지 않고 게시 할 것입니다. 나는 그것을 읽기 쉽게하기 위해 그렇게했다. –

관련 문제