访问由ajax发送的php中的json

时间:2013-07-15 16:09:12

标签: php ajax json

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

下面代码中的第一行告诉我:{"id":1,"email":"asd@qwe.co.uk","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是测试,因为我想检查用户是否传递了正确的详细信息,然后我将返回'loggedin' => 1左右的json对象,如果不是0

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

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

1 个答案:

答案 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 == 'asd@qwe.co.uk' && $data->password = '1234')
{
    $output['loggedin'] = '1';
}

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

echo json_encode($output);
相关问题