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

Qt6 QML环境下JavaScript读取本地JSON文件失败求助

解决Qt6 QML中XMLHttpRequest读取本地JSON失败的问题

核心问题分析及解决方案

1. 文件路径错误

Qt QML中读取本地文件时,路径规则和普通JS环境不同:

  • 若文件打包在**Qt资源文件(.qrc)**中,必须以qrc:/作为路径前缀,例如qrc:/modpacks.json,否则无法定位文件。
  • 若文件在磁盘本地目录,需使用绝对路径,或通过file://协议指定,例如Windows下file:///C:/project/modpacks.json,Linux下file:///home/user/modpacks.json。

2. 错误的状态码判断逻辑

读取本地文件时,XMLHttpRequest的status字段不会返回HTTP标准的200(因为未经过HTTP服务器),通常会返回0。需修改判断条件:

var json_read = new XMLHttpRequest();

json_read.onreadystatechange = function() {
    if (json_read.readyState === XMLHttpRequest.DONE) {
        // 兼容本地文件的状态码判断
        if (json_read.status === 200 || json_read.status === 0) {
            try {
                var json = JSON.parse(json_read.responseText);
                console.log(json);
            } catch(e) {
                console.error("JSON解析失败:", e);
            }
        } else {
            console.error("请求失败,状态码:", json_read.status);
        }
    }
};

// 替换为正确的文件路径
json_read.open("GET", "qrc:/modpacks.json", true);
json_read.send();

3. 缺少错误监听排查

添加错误监听事件,快速定位问题根源:

// 监听请求错误
json_read.onerror = function() {
    console.error("请求发生未知错误");
};

// 监听超时
json_read.ontimeout = function() {
    console.error("请求超时");
};

4. 替代方案:使用Qt内置FileIO组件

Qt QML提供了更适合本地文件操作的FileIO组件(需导入Qt.labs.io模块),比XMLHttpRequest更简洁可靠:

import Qt.labs.io 1.0

FileIO {
    id: fileReader
    source: "qrc:/modpacks.json"
    onReadFinished: {
        if (status === FileIO.NoError) {
            var json = JSON.parse(content);
            console.log(json);
        } else {
            console.error("文件读取失败:", errorString);
        }
    }
}

// 触发读取示例
Button {
    text: "读取JSON"
    onClicked: fileReader.read()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:02:14