AJAX请求json失败

时间:2015-02-20 17:12:53

标签: javascript php jquery ajax json

我遇到ajax请求的问题,当我使用属性dataType执行请求时:' json',我的响应带有错误,parsererror,我在PHP中的函数返回像json_encode这样的数据( ),请问,你能帮帮我吗?当我在没有属性dataType的情况下执行请求时:' json'我的数据是所有文档HTML。

我的要求:

                var dataAr = {Latitude: Latitude, Longitude: Longitude};/
                console.log(dataAr);
                $.ajax({
                    data: dataAr,
                    dataType: 'json',
                    type: 'POST',
                    url: 'http://localhost/GPS/Server.php/GPS/Coords',
                    success: function (data, response) {
                        console.log('Data: '+data);
                        console.log('Response: '+response);

                    },
                    error: function  (textStatus, errorThrown) {
                        console.log('Status: '+textStatus);
                        console.log('Error: '+errorThrown);                            
                    }
                });

我在PHP中的功能:

class GPS 
{
    function Coords()
    {
        $Res=$_POST['data'];
        $Latitude=$_POST['Latitude'];
        $Longitude=$_POST['Longitude'];

        return json_encode($Res);            
    }
}

2 个答案:

答案 0 :(得分:0)

尝试使用content-type

function Coords()
{
    $Res=$_POST['data'];
    $Latitude=$_POST['Latitude'];
    $Longitude=$_POST['Longitude'];

    header('Content-Type: application/json'); // <-- HERE
    return json_encode($Res);            
}

答案 1 :(得分:0)

$ _POST变量在您发送的内容中具有相同的名称,而不是&#39;数据&#39;。它不清楚你想要返回什么,所以例如以下只返回带有输入值的数组:

class GPS 
{
    function Coords()
    {
    $Latitude=$_POST['Latitude'];
    $Longitude=$_POST['Longitude'];
    $result = array( $Latitude, $longitude );

    header('Content-Type: application/json');
    echo json_encode($result);            
    }
}
相关问题