JQuery USES Ajax to get sample code for json formatted data

  • 2020-03-29 23:59:54
  • OfStack

JSON(JavaScript Object Notation) is a lightweight data interchange format. The JSONM file contains information about names and values. Sometimes we need to read data files in JSON format, which can be implemented in jQuery using Ajax or the $.getjson () method.

The next step is to use jQuery to read the JSON data format information in the music.txt file.
First, the contents of music.txt are as follows:
 
[ 
{"optionKey":"1", "optionValue":"Canon in D"}, 
{"optionKey":"2", "optionValue":"Wind Song"}, 
{"optionKey":"3", "optionValue":"Wings"} 
] 

The following is the HTML code:
 
<div> Click the button to get JSON data </div> 
<input type="button" id="button" value=" determine " /> 
<div id="result"></div> 

JQuery code to get JSON data using Ajax:
 
$(document).ready(function(){ 
$('#button').click(function(){ 
$.ajax({ 
type:"GET", 
url:"music.txt", 
dataType:"json", 
success:function(data){ 
var music="<ul>"; 
//I represents the index position in data, and n represents the object containing the information
$.each(data,function(i,n){ 
//Gets the value in the object whose property is optionsValue
music+="<li>"+n["optionValue"]+"</li>"; 
}); 
music+="</ul>"; 
$('#result').append(music); 
} 
}); 
return false; 
}); 
}); 

Of course, you can also use the $.getjson () method to keep the code simple:
 
$(document).ready(function(){ 
$('#button').click(function(){ 
$.getJSON('music.txt',function(data){ 
var music="<ul>"; 
$.each(data,function(i,n){ 
music+="<li>"+n["optionValue"]+"</li>"; 
}); 
music+="</ul>"; 
$('#result').append(music); 
}); 
return false; 
}); 
}); 

Related articles: