2014-10-21 4 views
0
에서 디코딩 JSON 문자열

내가 가지고있는 PHP를 내 자바 스크립트에서 (POST) 전송 다음 JSON은자바 스크립트에서 PHP

// 기능 다음은이 버튼을 클릭하고 URL을 호출
function boardToJSON() { 
    return JSON.stringify({ 
     "pieces" : gPieces,   // gpieces and gdestinations is an array 
     "destinations" : gDestinations, 
     "boardSize" : kBoardHeight  // boardSize is an integer value 9 

    }); 

는로 패스를 포함한다 PHP 파일. 서버 측에

function makeMove() { 
    var move; 
    $.ajax({ 
     type: 'POST', 
     url: url, 
     contentType: "application/json", 
     dataType: "json", 
     async: false, 
     data: boardToJSON(), 
     success: function(msg) { 
      move = msg;  
     }, 
     error: function(jqXHR, exception) { 
      if (jqXHR.status === 0) { 
       alert('Unable to connect.\n Verify Network.'); 
      } else if (jqXHR.status == 404) { 
       alert('Requested URL of HalmaAI not found. [404]'); 
      } else if (jqXHR.status == 500) { 
       alert('Internal Server Error [500].'); 
      } else if (exception === 'parsererror') { 
       alert('Data from HalmaAI was not JSON :(Parse failed.'); 
      } else if (exception === 'timeout') { 
       alert('Time out error.'); 
      } else if (exception === 'abort') { 
       alert('Ajax request aborted.'); 
      } else { 
       alert('Uncaught Error.\n' + jqXHR.responseText); 
      } 
     } 

    }); 

(PHP에서) 나는이

$jsonString = file_get_contents("php://input"); 
$myJson = json_decode($jsonString); 

echo $myJson["boardSize"]; // also tried $myJson.boardSize etc 

문제처럼 그걸 얻기 위해 시도하고 내가 PHP에서 JSON을 디코딩 할 수없는 생각이다. 누군가 나를 안내 할 수 있을까요? 감사합니다

+1

모르겠다. JSON을 게시하고 있지만 POST에서 파일을받지 못하는 파일에서 JSON을로드하려고 시도하는 PHP가 나타납니다. – Utkanos

+2

@Utkanos는 원시 게시물 본문입니다 ... – PeeHaa

+0

어떻게 데이터를 보냅니 까? 'var_dump()'는 당신에게 무엇을 말했습니까? – PeeHaa

답변

1

AJAX 요청의 contentType 속성을 application/json으로 설정해야합니다. 이렇게하면 원시 입력을 사용하여 서버가 $_POST을 채우려 고 시도하지 않도록 요청시 적절한 헤더가 설정됩니다.

function makeMove() { 
    var move; 
    $.ajax({ 
     type: 'POST', 
     url: url, 
     contentType: "application/json" 
     dataType: "json", 
     async: false, 
     data: boardToJSON(), 
     success: function(msg) { 
      move = msg;  
     } 
    }); 
} 

가정이 당신의 boardSize 속성에 액세스 할 수 있습니다, 작동 :

$myJson->boardSize; 

당신이 가진 또 다른 문제는 dataType: "json"를 지정하기 때문에 확실이 다시 유효한 JSON을 보낼 수 있도록 할 필요가있는 당신을 현재 없습니다.

이 유효 JSON되지 않습니다 :

echo $myJson["boardSize"]; 

이 (물론 이것은 사소한 예입니다) 다음과 같습니다

$returnObj = new stdClass(); 
$returnObj->boardSize = $myJson->boardSize; 
echo json_encode($returnObj); 
+0

이제 어떻게 boardSize의 가치를 얻을 수 있습니까? – farhangdon

+0

@farhangdon 죄송합니다. 이것을 보여주기 위해 나의 대답이 업데이트되었습니다. –

+0

아니요, 반환 된 데이터가 Json이 아니라고합니다. – farhangdon

0

당신이 PHP의 배열에 JSON을 디코딩하려는 경우, 당신은 설정해야합니다 제 2 인수는 json_decode ~ true입니다.
예 :

$jsonString = file_get_contents("php://input"); 
$myJson = json_decode($jsonString, true); 
echo $myJson["boardSize"]; 
관련 문제