1

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 是测试,因为我想检查用户是否传递了正确的详细信息,然后我将返回 json 对象'loggedin' => 1左右,如果没有0

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

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

4

1 回答 1

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);
于 2013-07-15T16:14:41.227 回答