未解决的ReferenceError: $ is not defined问题:JavaScript调用PHP示例排查
解决JavaScript调用PHP接口时的
$ is not defined及PHP未执行问题 我来帮你排查这个问题,你遇到的ReferenceError: $ is not defined以及PHP未执行的问题,主要是代码里的几处语法错误和资源加载逻辑错误导致的,咱们一步步来修复:
核心问题分析
- jQuery未正确加载/代码执行时机错误:你修改后的代码里,
index.js文件中错误地加入了<script>标签,这会导致JS语法解析失败;同时index.html重复引入了index.js,打乱了资源加载顺序。 - PHP文件混入前端代码:
index.php里添加的<script>标签完全多余,会导致返回的响应格式混乱,JS无法正确处理。 - 响应格式不匹配:你的JS代码期望PHP返回带
status字段的对象,但原PHP只返回字符串,逻辑判断会失效。
修复后的正确文件内容
1. index.html
修复字符编码引号错误,确保jQuery先加载,且只引入一次index.js:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello world</title> <!-- 先加载jQuery,确保$可用 --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <!-- 在body末尾引入index.js,确保DOM加载完成 --> <script src="index.js"></script> </body> </html>
2. index.js
移除错误的<script>标签,用$(document).ready确保代码在jQuery加载完成后执行,同时指定响应格式为JSON:
$(document).ready(function(){ alert("Hello world from javascript!"); console.log('Debug: JS code is running'); var myip = "192.168.1.20"; var myfile = "My_file_name"; $.get('index.php', { paramIp: myip, fileSource: myfile }, function(response) { // 解析JSON格式的响应 if (response.status === 'success') { alert("PHP returns OK"); } else { alert("PHP returns ERROR"); } }, 'json'); // 指定响应格式为JSON });
3. index.php
移除多余的前端标签,返回标准JSON格式响应,确保JS能正确解析:
<?php // 设置响应头为JSON格式 header('Content-Type: application/json'); $paramIp = isset($_GET['paramIp']) ? $_GET['paramIp'] : false; $fileSource = isset($_GET['fileSource']) ? $_GET['fileSource'] : ""; // 确保日志文件可写(注意服务器权限) $logFile = "log_messages.txt"; $fp = fopen($logFile, "a"); if ($fp) { $date = (new DateTime("NOW"))->format("y-m-d H:i:s"); fwrite($fp, $date . " index.php paramIp = " . $paramIp . ", fileSource = " . $fileSource . PHP_EOL); fclose($fp); // 返回成功状态 echo json_encode(['status' => 'success', 'data' => $fileSource]); } else { // 返回错误状态 echo json_encode(['status' => 'error', 'msg' => '无法写入日志文件']); } ?>
测试步骤
- 确保你的本地服务器(如XAMPP/WAMP)正常运行,文件放在正确的目录下(
localhost/myweb/mytest/example01/)。 - 访问
localhost/myweb/mytest/example01/index.html,会先弹出Hello world from javascript!。 - 随后会弹出
PHP returns OK,同时检查log_messages.txt文件,应该能看到写入的日志信息。 - 如果日志文件未生成,检查服务器对该目录的写入权限。
内容的提问来源于stack exchange,提问作者jstechg
相关产品推荐
相关产品推荐

