JSON (JavaScript Object Notation) is a lightweight data exchange format. The JSONM file contains information about "name" and "value". Sometimes we need to read data files in JSON format, which can be achieved using Ajax or the $.getJSON() method in jQuery.
The following uses jQuery to read the JSON data format information in the music.txt file.
First, the content in music.txt is as follows:
[
{"optionKey":"1", "optionValue":"Canon in D"},
{"optionKey":"2", "optionValue":"Wind Song"},
{"optionKey":"3", "optionValue":"Wings"}
]
The following is the HTML code:
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="
";
//i represents the index position in data, n represents the object containing the information
$.each (data,function(i,n){
//Get the value of the object whose attribute is optionsValue
music ="- " n["optionValue"] "
";
});
music ="
";
$('#result').append(music);
}
});
return false;
});
});
Of course, you can also use the $.getJSON() method, the code is simpler:
$(document).ready(function(){
$('#button').click(function( ){
$.getJSON('music.txt',function(data){
var music="
";
$.each(data,function(i,n){
music ="- " n["optionValue"] "
";
});
music ="
";
$('# result').append(music);
});
return false;
});
});