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

调用JavaScript profile函数二次报错:Uncaught TypeError问题排查

问题原因分析与解决方案

核心原因:全局变量污染

在profile_detail函数中,你直接使用了未声明的profile变量:

profile = JSON.parse(xhr.responseText);

由于没有用var、let或const声明,这个profile会自动成为全局变量。

第一次调用profile()函数时,会执行profile_detail(),此时全局作用域里原本作为函数的profile会被覆盖成JSON解析后的对象。当你第二次触发点击事件时,profile已经不再是函数,而是一个普通对象,因此抛出TypeError: profile is not a function的错误。

另外,xhr变量同样未声明,也存在全局污染风险,建议一并修复。

修复方案

给profile_detail里的变量添加声明,限制其作用域:

function profile_detail(){
    // 声明xhr变量,避免全局污染
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost/CI-social-media/index.php/profile_detail", false);

    xhr.onload = () => {
        if (xhr.status == 200) {
            if (xhr.response) {
                // 声明profile变量,限制在当前作用域内
                const profile = JSON.parse(xhr.responseText);
                console.log(xhr.response);
                console.log(profile);

                document.getElementById("profile_photo").src = profile[0]["profile"];
                document.getElementById("profile_name").innerHTML = profile[0]["display_name"];
                document.getElementById("username").innerHTML = "@"+ profile[0]["user_name"];
            }
            else {
                alert("something want wrong try agin later")
            }
        }
        else {
            alert("Something Want Wrong Try agin");
        }
    }

    xhr.send();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:20:46