XMLHttpRequest 操作 JSON 文件 [关闭]

Posted

技术标签:

【中文标题】XMLHttpRequest 操作 JSON 文件 [关闭]【英文标题】:XMLHttpRequest manipulate JSON-File [closed] 【发布时间】:2022-01-02 14:20:36 【问题描述】:

尝试执行 XMLHttprequest 来操作 JSON 并将其保存在我的本地驱动器上。

代码如下:

   
     function xml()
        var xhr = new XMLHttpRequest(),
            jsonArr,
            method = "GET",
            jsonRequestURL = "win_lose.json";
        price = $('#price').val();
        xhr.open(method, jsonRequestURL, true);
        xhr.onreadystatechange = function () 
            if (xhr.readyState == 4 && xhr.status == 200) 
                // we convert your JSON into javascript object
                jsonArr = JSON.parse(xhr.responseText);
                var index = jsonArr.findIndex(obj => obj.name===price);
                jsonArr.splice(index);
                console.log(price);
                console.log(index);
                xhr.open("POST", jsonRequestURL, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send("jsonTxt=" + JSON.stringify(jsonArr));
            

        ;
        xhr.send(null);
    

我的 JSON 文件:

[
   
      "state": "geschlossen",
      "number": 1,
      "class": "A",
      "price": 10
    ,
    
      "state": "geschlossen",
      "number": 2,
      "class": "B",
      "price": 20
    ,
    
      "state": "geschlossen",
      "number": 3,
      "class": "C",
      "price": 30
    
  ]

findIndex 如果我输入值 10,20 或 30,每次索引 -1 都无关紧要,但我希望: price : 10 -> index 0 ; price : 20 -> index 1 ; price : 30 -> index 2 ;

那么 findIndex 的问题在哪里?

【问题讨论】:

【参考方案1】:

看起来你必须在这里使用obj.price 而不是obj.namevar index = jsonArr.findIndex(obj => obj.name===price);

【讨论】:

是的,谢谢队友是帽子 var index = jsonArr.findIndex(obj => obj.price==price);只有两个“=”而不是三个

以上是关于XMLHttpRequest 操作 JSON 文件 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

为啥我不能使用 XMLHttpRequest 从本地网络获取 JSON 文件? [复制]

XMLHttpRequest + JSON + 文件上传 + axios

XMLHttpRequest下载文件方法中添加处理服务器返回json格式的错误提示信息

XMLHttpRequest JSON Post 格式为 urlencoded

加载 JSON 适用于 XMLHttpRequest 但不适用于 jQuery

从源“null”访问“http://github/..file.json”处的 XMLHttpRequest 已被 CORS 策略阻止: