使用Ajax时if语句简单的问题

问题描述 投票:1回答:2

我有一个小而令人沮丧的问题(尽管我认为这可能是小而愚蠢的),我已经研究了几个小时,尝试了不同的方法,切换了变量,并做了一些事情来看看它是否会工作。

我有一个XMLHttpRequest对象,并且我有一个API返回咒语及其效果。但是,在generateSpellBody函数中,if() else()语句未正确执行。我一直得到结果not a spell,无论我如何更改条件,尝试不同的方法,都尝试过indexOf()json.parse等。我一直仅在else内部获得test.innerHTML条件的结果>

const spells = 'https://{my-spells-api-and-auth-key}';
const spellBtn = document.querySelector('.spell-btn');
const spellTextBox = document.querySelector('#spell-text');
let test = document.querySelector('.test');

function getJson (url, callback) {
    const xhr = new XMLHttpRequest;
    xhr.open('GET', url);
    xhr.onload = () => {
        if (xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            return callback(data);
        }
    };
    xhr.send();
}

function generateSpellBody (data) {

     data.map(dat => {
         if (dat.spell === spellTextBox.value) {
            console.log(dat.spell);
            test.innerHTML = dat.spell;
        }
        else {
            test.innerHTML = 'not a spell';
        }

    });

}

spellBtn.addEventListener('click', (e) => {
    e.preventDefault();
    getJson(spells, generateSpellBody);
});

HTML:

    <form method='get'>
        <div class="form-group">
            <input type="text" class="form-control" id="spell-text" placeholder="Enter spell">
        </div>
        <button type="submit" class="spell-btn btn btn-default btn-light">Do spell</button>
    </form>

    <div class="test"></div>

返回部分JSON数据:

[
    {
        "_id": "5b74ebd5fb6fc0739646754c",
        "spell": "Aberto",
        "type": "Charm",
        "effect": "opens objects"
    },
    {
        "_id": "5b74ecfa3228320021ab622b",
        "spell": "Accio",
        "type": "Charm",
        "effect": "Summons an object",
        "__v": 0
    },
    {
        "_id": "5b74ed2f3228320021ab622c",
        "spell": "Age Line",
        "type": "Enchantment",
        "effect": "Hides things from younger people",
        "__v": 0
    },
    {
        "_id": "5b74ed453228320021ab622d",
        "spell": "Aguamenti",
        "type": "Charm",
        "effect": "shoots water from wand",
        "__v": 0
    }
]

我有一个小而令人沮丧的问题(尽管我认为这可能是个小而愚蠢的问题,而且我已经研究了几个小时,尝试了不同的方法,切换了变量,并对...进行了一些处理……]]

javascript html ajax
2个回答
0
投票
 function generateSpellBody (data) {
    var newArray = data.map(dat=>dat.spell ===spellTextBox.value?dat.spell:'not a spell')
    const arrayStr = newData.join(' ');
    test.innerHTML=arrayStr;
 };

0
投票

首先,map函数不是在此处使用的正确函数。使用for循环,第二件事是,当if条件的值为假时,将运行else块,并为您提供输出not a spell。因此,即使您找到了正确的咒语,在循环的下一个迭代中,else块也会运行并用not a spell覆盖正确的咒语。

© www.soinside.com 2019 - 2024. All rights reserved.