简体   繁体   English

Json 中的 Javascript 搜索

[英]Javascript search in Json

I am totally new to Javascript and I have a small problem here.我对 Javascript 完全陌生,这里有一个小问题。 When I am trying to get from Element value it works correctly(console shows value fine), but when I am trying to add this variable to the JSON It says: "Uncaught TypeError: Cannot read property 'meanings' of undefined at XMLHttpRequest.request.onload."当我尝试从 Element 值中获取它时它工作正常(控制台显示值很好),但是当我尝试将此变量添加到 JSON 时它说:“未捕获的类型错误:无法读取 XMLHttpRequest.request 处未定义的属性‘含义’ 。负载。”

Here is the code:这是代码:

    // Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://raw.githubusercontent.com/davidluzgouveia/kanji-data/master/kanji-jouyou.json', true)

request.onload = function () {
  // Begin accessing JSON data here
  
  // Begin accessing JSON data here
var data = JSON.parse(this.response)   
 
 var kanji = document.getElementById("kanji").value;  

 console.log(kanji);
 



 //  document.getElementById("on").innerHTML = data.日.readings_on;   ------ WORKS CORRECTLY
 document.getElementById("reading").innerHTML = data.kanji.meanings; ------ DOESN'T WORK
 document.getElementById("kun").innerHTML = data.kanji.readings_kun; ------ DOESN'T WORK
 document.getElementById("on").innerHTML = data.kanji.readings_on;   ------ DOESN'T WORK
 

 
 **// IF INSTEAD OF kanji I will put something else for example 日 my code works as it should.**

 
 }

request.send();

You could try fetch .你可以试试fetch See the example below:请参阅下面的示例:

 fetch('https://raw.githubusercontent.com/davidluzgouveia/kanji-data/master/kanji-jouyou.json') .then(response => response.json()) .then(data => { let kanji = document.getElementById('kanji').value; console.log('Success: ', data[kanji].meanings); // json data returned, write the rest of your code here // .... }) .catch((error) => { console.error('Error:', error); });
 <input type="text" id="kanji" value="日" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM