json 取数据时部落API错误响应冲突

fhg3lkii  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(178)

VM 100:1未捕获语法错误:意外的标记“E”,“错误:“不是有效的JSON
at JSON.parse()
at Object.success( AJAX .js:15:21)
at c(Jquery.js:2:25266)
at Object.fireWith [as resolveWith](Jquery.js:2:26015)
at l(Jquery.js:2:77721)
at XMLHttpRequest.(Jquery.js:2:80204)
我的PHP代码

<?php

$apiKey = file_get_contents('./token.txt');
$playerTag = '%23'.$_GET['tag'];


$url = "https://api.clashofclans.com/v1/players/{$playerTag}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $apiKey]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CAINFO, 'F:\Programming\Wamp\www\clashofclan\cacert.pem');

$response = curl_exec($ch);
curl_close($ch);
$data = $response;


if ($response === false) 
{
    echo 'Error: ' . curl_error($ch);
} 
else {
    
    if (isset($data)) 
    {
        $dataEn = json_encode($data);
        echo $dataEn;
    }
    else 
    {
        echo 'Error: Unable to fetch player information.';
    }
}
?>

在 AJAX / JS

// 9CQ8R2J89
$('#submit').click(function()
{ 
  

  tag = $('#tag').val()
  tag = tag.toUpperCase();
  $.ajax({
    
     url : './get.php',
     method : 'GET',
     data: { tag: tag },
     success : function(res)
     {
        main = JSON.parse(res)
      $('#res').html(main);
     }

  })

})

我尝试了我所知道的一切,也尝试了chat-gpt,但错误仍然一次又一次地继续

hjqgdpho

hjqgdpho1#

首先将所有响应转换为JSON,JS代码要做的第一件事就是尝试将响应JSON转换为js数据。如果它得到一个错误,那一行将像这样失败

if ($response === false) 
{
    echo json_encode( ['errorCode => 1, 
                       'errorMsg' => curl_error($ch)
                      ] 
                    );
} else {
    
    if (isset($data)) 
    {
        echo json_encode(['errorCode' => 0,
                          'response' => $data);
    } else  {
        echo json_encode( ['errorCode => 2, 
                           'errorMsg' => 'Unable to fetch player information.'
                          ] 
                        );
    }
}

现在在Javascript中,在执行其他操作之前查找错误,否则继续执行主进程

$('#submit').click(function(){ 
    tag = $('#tag').val();
    tag = tag.toUpperCase();
    $.ajax({
        url : './get.php',
        method : 'GET',
        data: { tag: tag },
        success : function(res) {
            main = JSON.parse(res);
            if ( main.errorCode == 0){
                $('#res').html(main);
            } else {
                // error found, so do whatever is necessary here
        }
    });
});

还要注意附加的;

相关问题