我正在编写一个JavaScript代码,其中在条件执行后将提供警报
我在ajax和json上引用了一些youtube视频,并编写了代码,其中我成功地从网站记录了数据并发送了自动警报消息。我的问题是,每当我在if语句中添加相同的警报消息时,警报都不会执行。
我尝试使用f12的开发人员工具并调试了似乎数据未进入循环的代码。
请帮助我
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData);
if (ourData = "cat") {
alert(" take action");
};
ourRequest.send();
}
应该在链接https://learnwebcode.github.io/json-example/animals-1.json的json文件中找到cat时生成警报。
答案 0 :(得分:0)
我在这里发布答案,而不是发表评论,因为它太长了。
如果格式不正确,则应使用比较运算符==
或===
(“更好”)。如果您使用正确的运算符来更正您的if,因为您使用了=
这是情感运算符。
通过我检查数据的方式,您应该遍历对象列表并检查“ species”属性。像这样if(ourData.species == "cat")
。
您的代码应如下所示:
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json', true);
ourRequest.onload = function () {
// Request finished. Do processing here.
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData);
// loop over each "animal" element
ourData.forEach(function (element) {
if (element.species === "cat") {
alert(" take action");
};
});
};
ourRequest.send();
希望有帮助。