Answer the question
In order to leave comments, you need to log in
How to display data from JSON by including a variable?
Hello.
Please tell me, is it possible to somehow connect a variable to take data from a JSON file by a specific key?!
In the comments in the file I tried to expand the question.
Sample HTML, JS, jQuery code:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- <script src="load.js"></script> -->
</head>
<body>
<ul>
<li id="one">One</li>
<li id="two">Two</li>
</ul>
<script>
$(document).ready(function(){
var clickId, xmlhttp, text;
$('li').click(function(){
clickId = (this.id); // получаем id элемента <li>, по которому совершен клик
xmlhttp = new XMLHttpRequest(); // по примеру https://www.w3schools.com/js/js_json_parse.asp
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
text = JSON.parse(this.responseText);
document.getElementById("first").innerHTML = text.one; // здесь текст выводится из json.txt по заранене прописанному ключу
document.getElementById("second").innerHTML = text.clickId; // а здесь подключается переменная clickId (как ключ), которой присваивается определенный id, по которому и хотелось бы из json.txt брать данные. Но,если бы это работало, то вопрос бы не задавался
}
};
xmlhttp.open("GET", "json.txt", true);
xmlhttp.send();
});
});
</script>
<p id="first"></p>
<p id="second"></p>
</body>
</html>
{
"one":"один",
"two":"два"
}
Answer the question
In order to leave comments, you need to log in
question 1: connect a variable to something specific - I suspect you have something like this hotote - :
var rawText = '{"one":1,"two":2,"four":4}';
var jsonObj = JSON.parse(rawText);
var key = 'two';
var val = null;
for (prop in jsonObj) {
if (prop.match(key)) {
val = jsonObj[prop];
}
}
console.log('key: ' + key);
console.log('val: ' + val);
var rawText = '{"key":["one","two","three"]}';
var jsonObj = JSON.parse(rawText);
var key = 'key';
var val = jsonObj[key].join(',');
console.log('val: ' +val );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question