【问题标题】:XMLHttpRequest manipulate JSON-File [closed]XMLHttpRequest 操作 JSON 文件 [关闭]
【发布时间】: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 的问题在哪里?

【问题讨论】:

    标签: javascript json ajax


    【解决方案1】:

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

    【讨论】:

    • 是的,谢谢队友是帽子 var index = jsonArr.findIndex(obj => obj.price==price);只有两个“=”而不是三个
    猜你喜欢
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多