2013-07-15 3 views
1

js 파일에서 나는 PHP 파일에 JSON 개체를 보내고 있지만 전송 된 개체에 액세스하는 방법을 모르겠다.PHP에서 JSON에 액세스 아약스에 의해

코드

첫 번째 줄은 아래에 저를 줄 :

<?php 

header('Content-type: application/json'); 
$ret=$_GET['data']; 

$ret=json_decode($ret, true); 

echo '['.json_encode($ret[0]).']'; 

?> 

PHP는 테스트입니다 내가 확인하기를 원하기 때문에, : {"id":1,"email":"[email protected]","password":"xxxx","location":"London"}

JS가

app.showAlert(JSON.stringify(profile)); 

    $.ajax({ 
     type: "GET", 
     url:"http://www.domain.co.uk/test-login.php", 
     dataType: 'jsonp', 
     data: { data: JSON.stringify(profile) }, 
     success:function(json){ 
      // do stuff with json (in this case an array) 
      app.showAlert(JSON.stringify(json), "Login ok"); 
     }, 
     error:function(){ 
      app.showAlert("Login faild", "Wrong username or password. Please try again."); 
     }, 
    }); 

PHP 파일을 파일 사용자가 올바른 정보를 전달하면으로 json 객체를 반환합니다.정도면 0

$ret=$_GET['profile'];으로이 개체에 액세스하려고했지만 도움이되지 않았습니다.

내 질문은 : json 개체를 전달하는 방법 및 PHP에서 액세스 할 수 있습니다.

+1

은 무엇 출력을 제공합니까? print_r의 결과물은 무엇을 제공합니까? –

+0

정확히 어디에서'print_r'을 사용해야합니까? 문제는 json 객체를받지 못하면 msg'Login faild'가 발생하기 때문에 어떤 일이 일어나고 있는지 단계별로 확인할 수 없다는 것입니다. – miszczu

+0

무슨 일이 일어나는지 더 잘 파악하기 위해 무엇을 설명 하는지를 인쇄하는 기본 아이디어 ... –

답변

1

당신이 원하는 것을하기 위해 아약스와 PHP를 모두 수정해야합니다. 성공 함수 내에서 성공/실패 여부를 테스트하기 위해 자바 스크립트를 변경했습니다. PHP에서 JSON을 반환하는 경우 오류 이벤트에서 실패한 비밀번호를 처리하지 않으려 고합니다.

PHP의 경우 입출력이 엇갈린 것처럼 보입니다. 보시다시피 입력은 $data 변수로 디코드되고 출력은 인코딩되고 출력 될 때까지 $output의 배열입니다.

$.ajax({ 
    type: "GET", 
    url:"http://www.domain.co.uk/test-login.php", 
    dataType: 'jsonp', 
    data: { data: JSON.stringify(profile) }, 
    success:function(json){ 
     // do stuff with json (in this case an array) 
     if(json.loggedin == '1'){ 
      alert("logged in"); 
     } else { 
      alert("failed to login"); 
     } 
    } 
}); 

PHP :

$output = array('loggedin' => 0); 
$data = json_decode($_GET['data']); 

// this shows how to access the data 
if($data->email == '[email protected]' && $data->password = '1234') 
{ 
    $output['loggedin'] = '1'; 
} 

header('Content-type: application/json'); 

echo json_encode($output); 
관련 문제