You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch API调用PHP接口时,如何获取浏览器预览区的纯返回数据?

问题分析与解决方法

你的核心问题是PHP接口返回结果混入了HTML内容,导致前端用res.json()解析时触发"unexpected token"错误——根源在于PHP脚本里require_once('../index.php');加载了前端入口文件(该文件会输出HTML),使得接口返回内容是HTML文本+你需要的接口数据的混合体,而AJAX调用可能对应未引入该文件的PHP脚本,所以没出现问题。

以下是具体修复步骤:

1. 移除不必要的前端入口文件引用

直接删除PHP中加载前端页面的代码:

// 删掉这行,它会输出index.php里的HTML内容
require_once('../index.php');

如果app_path函数依赖index.php中的定义,不要加载整个index.php,而是单独提取app_path函数或相关配置到公共工具文件(比如Config/helpers.php),再引入该文件。

2. 让PHP返回标准JSON格式数据

前端用res.json()解析,所以PHP必须返回合法JSON,并设置正确的响应头:
修改后的PHP代码:

<?php
// 引入必要的配置文件(如果app_path需要单独定义,先引入定义它的文件)
require_once(app_path('Config/Constants.php'));

// 设置JSON响应头,告诉浏览器返回的是JSON格式
header('Content-Type: application/json');

// 关闭错误输出,避免PHP警告/错误混入返回内容
error_reporting(0);
ini_set('display_errors', 0);

if(isset($_GET['request'])){
    $params = isset($_GET['params']) ? $_GET['params'] : 'no_params=true';

    function getIt($request,$params){
        $url = HST.$request.'api_key='.AKY.$params;
        $ch = curl_init();
        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0
        ];
        curl_setopt_array($ch,$options);
        $results = curl_exec($ch);
        curl_close($ch);

        // 将结果转为JSON格式返回
        return json_encode([
            'success' => true,
            'data' => $results ?: 'No data returned'
        ]);
    }

    echo getIt($_GET['request'], $params);
}else{
    // 错误场景也返回JSON
    echo json_encode([
        'success' => false,
        'message' => 'Request Invalid Or Does Not Exist'
    ]);
}

3. 前端Fetch代码优化(增加错误处理)

async function getIt(url) {
    try {
        const response = await fetch(url);
        // 检查HTTP响应状态是否正常
        if (!response.ok) {
            throw new Error(`请求失败,状态码:${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('请求出错:', error);
        throw error; // 让调用方可以处理错误
    }
}

// 调用示例
getIt('php/fknit.php?request=/trending/all/day')
    .then(results => {
        console.log(results);
    })
    .catch(err => {
        console.error('获取结果失败:', err);
    });

内容的提问来源于stack exchange,提问作者Hoofer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:30:53