使用jQuery AJAX请求PHP后端返回完整PHP代码页面问题求助
问题解决:PHP文件未执行、返回源码的原因及修复方案
核心问题原因
你同时启动了两个独立服务器:Live Server(静态文件服务,默认端口多为5500)和PHP内置服务器(localhost:4000)。当用Live Server打开index.html时,页面的AJAX请求是向Live Server发起的,而Live Server仅会返回data.json.php的原始文件内容,不会解析执行PHP代码。
修复步骤
1. 统一通过PHP服务器访问所有资源
- 关闭Live Server
- 确保
index.html和data.json.php都在你执行php -S localhost:4000命令的目录下 - 在浏览器中访问
http://localhost:4000/index.html,此时AJAX请求会被PHP服务器处理,执行data.json.php的代码并返回正确结果
2. 修正PHP代码的语法错误
你的PHP代码中$output = "hello"后缺少分号,会导致PHP执行报错,修改后的代码:
<?php header('Content-Type: application/json'); $output = "hello"; echo json_encode($output); ?>
3. 优化AJAX请求(便于调试)
添加错误处理和明确的请求配置,方便排查后续问题:
$(function () { $.ajax({ url: "data.json.php", type: "GET", dataType: "json", success: function(result){ alert(result); }, error: function(xhr, status, error) { console.log("请求错误信息:", error); console.log("服务器返回内容:", xhr.responseText); } }); });
额外说明
PHP内置服务器会对.php后缀的文件进行解析执行,对.html等静态文件则直接返回内容。只要所有请求都通过PHP服务器发起,就能实现前端与后端的正确交互。
内容的提问来源于stack exchange,提问作者Alex G.
相关产品推荐
相关产品推荐

