2013-07-15 41 views
1

js文件我发送json对象到php文件,但我不知道如何访问发送的对象。在ajax访问php访问json

以下代码

第一行给我说:{"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文件:

<?php 

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

$ret=json_decode($ret, true); 

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

?> 

PHP是考验,因为我要检查如果用户传递正确的细节,那么我将返回带有的json对象左右,如果不0

我也试图通过$ret=$_GET['profile'];访问这个对象,但它并没有帮助。

我的问题是:如何传递json对象并在php中访问它。

+1

什么是输出给你? print_r的输出给你什么? –

+0

在哪里我应该使用'print_r'?问题是我不能一步一步检查发生了什么,因为如果我没有收到json对象,我会收到msg'Login faild'。 – miszczu

+0

这个基本的想法是打印出你所描述的内容,以便更好地了解正在发生的事情。 –

回答

1

你需要修改ajax和PHP来让它做你想做的。我更改了Javascript以测试成功函数中的成功/失败。如果您从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);