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

AJAX请求的success回调函数无法触发,求技术排查与解决

问题排查与修复方案

你的代码里有几个关键问题导致AJAX回调不触发,逐一拆解:

一、PHP代码的致命问题

  1. 语法错误:if($_GET["command"] == "write") 后面未加{},导致后续fwrite语句脱离判断范围,还会引发括号不匹配的语法错误,直接让PHP返回500错误,AJAX无法正常解析响应。
  2. 输出非纯JSON内容:PHP文件里的<html>和<body>标签会和JSON内容一起输出,导致返回的不是合法JSON格式,AJAX的dataType:'json'解析失败,进入静默失败状态。
  3. 文件操作未关闭:fopen后没调用fclose($handle),可能引发文件锁定问题;且Write分支无任何输出,AJAX会一直等待响应直到超时。

修正后的PHP代码:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header("Access-Control-Allow-Methods: GET, POST, PUT");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 86400");

if($_SERVER['REQUEST_METHOD'] == 'GET'){
    if(isset($_GET["command"])){
        if($_GET["command"] == "write"){
            if(isset($_GET["data"])){
                $handle = fopen("homework_10.txt", "w");
                fwrite($handle, $_GET["data"]);
                fclose($handle);
                echo json_encode("写入成功");
            } else {
                echo json_encode("缺少data参数");
            }
        }
        if($_GET["command"] == "read"){
            $filePath = "homework_10.txt";
            if(file_exists($filePath)){
                $handle = fopen($filePath, "r");
                $printData = fread($handle, filesize($filePath));
                fclose($handle);
                echo json_encode($printData);
            } else {
                echo json_encode("文件不存在");
            }
        }
    } else {
        echo json_encode("缺少command参数");
    }
}
?>

二、AJAX代码的问题

  1. GET请求错误设置contentType:"application/json":GET参数通过URL传递,不需要这个头,设置后会导致请求格式异常。
  2. 重复解析JSON:dataType:'json'已经让jQuery自动将响应解析为JSON对象,再调用JSON.parse(result)会抛出解析错误,导致success回调执行失败。

修正后的AJAX&HTML代码:

<html>
    <head>
        <title>Homework 10</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
        <script>
            $(document).ready(function(){
                $("button:contains('Read')").click(function(){
                    $.ajax({
                        url:'你的PHP文件实际地址',
                        type: 'GET',
                        data: { command: 'read' },
                        dataType:'json',
                        success: function(result){
                            console.log(result);
                            $("#result").html("<pre>" + result  + "</pre>");
                        },
                        error: function(error){
                            console.log(error);
                            $("#result").html("<pre>请求错误:" + error.statusText + "</pre>");
                        }
                    });
                });
                $("button:contains('Write')").click(function() {
                    var dataToWrite = $("#answer").val();
                    $.ajax({
                        url: '你的PHP文件实际地址',
                        type: 'GET',
                        data: { command: 'write', data: dataToWrite },
                        dataType:'json',
                        success: function(result){
                            console.log(result);
                            $("#result").html("<pre>" + result + "</pre>");
                        },
                        error: function(error){
                            console.log(error);
                            $("#result").html("<pre>请求错误:" + error.statusText + "</pre>");
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <form id="PHP-input">
            <label id="fnlabel">Type file input here:</label>
            <input id="answer" type="text" name="fninput"/>
            <br>
            <button type="button">Read</button>
            <button type="button">Write</button>
        </form>
        <div id="result"></div>
    </body>
</html>

三、额外小问题修正

  • 表单id去掉空格:id="PHP input"改为id="PHP-input",避免选择器异常。
  • 移除Read按钮无效的onclick="write",防止干扰点击事件。
  • input标签id属性加引号:id = answer改为id="answer",符合HTML语法规范。

修改完成后,打开浏览器控制台(F12)查看Network标签的请求详情,可直观看到请求状态与响应内容,方便后续调试。

内容的提问来源于stack exchange,提问作者wsh</think_never_used_51bce0c785ca2f68081bfa7d91973934>

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:52:57