JSON (JavaScript Object notation) is a lightweight data interchange format. The Jsonm file contains information about name and value. Sometimes we need to read JSON-formatted data files, which can be implemented in jquery using Ajax or $.getjson () methods.
The following is used to read the JSON data format information in the Music.txt file using jquery.
First, the contents of the Music.txt are as follows:
Copy Code code as follows:
[
{"Optionkey": "1", "OptionValue": "Canon in D"},
{"Optionkey": "2", "OptionValue": "Wind Song"},
{"Optionkey": "3", "OptionValue": "Wings"}
]
Down is the HTML code:
Copy Code code as follows:
<div> Click on the button to get JSON data </div>
<input type= "button" id= "button" value= "OK"/>
<div id= "Result" ></div>
jquery code to get JSON data using Ajax:
Copy Code code as follows:
$ (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, N represents an object containing information
$.each (Data,function (i,n) {
Gets the value of the property in the object that is Optionsvalue
music+= "<li>" +n["OptionValue"]+ "</li>";
});
music+= "</ul>";
$ (' #result '). Append (music);
}
});
return false;
});
});
Of course, you can also use the $.getjson () method, the code is simple:
Copy Code code as follows:
$ (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;
});
});