无法从PHP的json_encode获取API数据,返回HTML或JSON解析错误求助
解决PHP json_encode返回HTML或JSON解析错误的问题
问题根源
- 前端
fetch默认用GET请求,但controller.php只处理POST参数,首次请求会触发输出mainpage.php的HTML内容,导致前端解析JSON时碰到<字符报错。 get_api函数返回的是第三方API的原始JSON字符串,再用json_encode包裹会把它转成JSON字符串类型,而非预期的JSON对象。- 没有设置正确的
Content-Type响应头,浏览器无法准确识别返回内容格式。
修正后的代码
controller.php
<?php // 先设置JSON响应头,确保返回内容被识别为JSON header('Content-Type: application/json; charset=utf-8'); // 仅处理POST请求的API逻辑 if ($_SERVER['REQUEST_METHOD'] === 'POST') { require('include/model.php'); if ($_POST['command'] === 'city') { $api_data = get_api(); // 直接输出API返回的JSON,无需再次编码 echo $api_data ?? json_encode(['error' => '缺少城市名称或API请求失败']); exit(); } } // GET请求返回页面内容 include('include/mainpage.php'); ?>
model.php
<?php function get_api() { // 校验城市名参数 if (!isset($_POST['cityname']) || empty(trim($_POST['cityname']))) { return json_encode(['error' => '请输入城市名称']); } // 对城市名URL编码,避免特殊字符导致API请求失败 $city = urlencode(trim($_POST['cityname'])); $api_key = "25a8988cc514c4753be58564848636a0"; $api_url = "https://api.openweathermap.org/data/2.5/weather?q={$city}&appid={$api_key}"; // 捕获API请求失败的情况 $api_data = @file_get_contents($api_url); if ($api_data === false) { return json_encode(['error' => '天气API请求失败']); } return $api_data; } ?>
mainpage.php
<script> // 示例:以POST方式传递参数请求天气数据 fetch('controller.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, // 传递command和cityname参数 body: new URLSearchParams({ command: 'city', cityname: 'Beijing' // 可替换为用户输入的城市名 }) }) .then(response => { if (!response.ok) { throw new Error('网络请求异常'); } return response.json(); }) .then(data => console.log('天气数据:', data)) .catch(error => console.error('请求错误:', error)); </script>
关键修改说明
- 给
controller.php添加Content-Type响应头,明确告知浏览器返回的是JSON格式。 - 区分GET/POST请求:POST处理API逻辑,GET返回页面,避免内容混淆。
- 去掉对第三方API返回JSON的二次
json_encode,直接输出原始JSON即可。 - 给城市名做
urlencode处理,防止空格、特殊字符破坏API请求链接。 - 增加参数校验和错误捕获,返回结构化的错误JSON,方便前端处理。
- 前端
fetch改为POST方式,并正确传递参数,确保后端能识别请求意图。
内容的提问来源于stack exchange,提问作者tracey02
相关产品推荐
相关产品推荐

