【问题标题】:AJAX request json failAJAX请求json失败
【发布时间】:2023-03-13 17:59:01
【问题描述】:

我的 ajax 请求有问题,当我使用属性 dataType: 'json' 进行请求时,我的响应出现错误,解析器错误,我在 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);            
    }
}

【问题讨论】:

  • 您是否使用 echo 将数据发送回您的 Ajax 函数?
  • @bobdye 在我的函数 PHP 中使用 echo 会发生同样的错误
  • 在浏览器控制台网络选项卡中检查实际请求。我怀疑你的路由也不对
  • @charlietfl 你在说我的网址吗?我不这么认为,但感谢您的评论,我只是在没有类和函数的“server.php”之类的本机代码中测试了我的请求,并且......不起作用

标签: javascript php jquery ajax json


【解决方案1】:

尝试使用content-type

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

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

【讨论】:

    【解决方案2】:

    $_POST 变量在您发送的内容中具有相同的名称,而不是“数据”。目前尚不清楚您要返回什么,因此例如,以下仅返回和数组与输入值:

    class GPS 
    {
        function Coords()
        {
        $Latitude=$_POST['Latitude'];
        $Longitude=$_POST['Longitude'];
        $result = array( $Latitude, $longitude );
    
        header('Content-Type: application/json');
        echo json_encode($result);            
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 2018-11-30
      • 1970-01-01
      • 2015-08-14
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多