简体   繁体   English

AJAX请求JSON失败

[英]AJAX request json fail

I have a problem with an ajax request, when I do the request with the property dataType: 'json', my response come with an error, parsererror, my function in PHP returns the data like json_encode(), pls, can you help me? 我对ajax请求有问题,当我使用属性dataType:'json'进行请求时,我的响应带有错误parsererror,我的PHP函数返回了json_encode()之类的数据,请问您可以帮我吗? when I do the request without property dataType: 'json' my data is ALL THE DOCUMENT HTML. 当我执行不带属性dataType:'json'的请求时,我的数据是ALL THE DOCUMENT HTML。

My request: 我的请求:

                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);                            
                    }
                });

My function in PHP: 我在PHP中的功能:

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

        return json_encode($Res);            
    }
}

Try using content-type : 尝试使用content-type

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

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

The $_POST variables have the same names at what you send in, not 'data'. $ _POST变量在您发送的内容上具有相同的名称,而不是'data'。 It's not clear what you are trying to return, so for example purposes the following just returns and array with the input values: 目前尚不清楚您要返回的内容,因此出于示例目的,以下内容仅返回并包含输入值的数组:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM