Sometimes we need to read data files in JSON format. In jQuery, Ajax or $. the getJSON () method is implemented. The following is a good example. For more information, see JSON (JavaScript Object Notation), which 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. In jQuery, we can use Ajax or $. getJSON.
Use jqueryto read the JSON data format information in the music.txt file.
First, the content in music.txt is as follows:
The Code is as follows:
[
{"OptionKey": "1", "optionValue": "Canon in D "},
{"OptionKey": "2", "optionValue": "Wind Song "},
{"OptionKey": "3", "optionValue": "Wings "}
]
The following is the HTML code:
The Code is as follows:
Click to obtain JSON data
JQuery code for retrieving JSON Data Using Ajax:
The Code is as follows:
$ (Document). ready (function (){
$ ('# Click'). click (function (){
$. Ajax ({
Type: "GET ",
Url: "music.txt ",
DataType: "json ",
Success: function (data ){
Var music ="
";
// I indicates the index position in data, and n indicates the object containing information
$. Each (data, function (I, n ){
// Obtain the value of optionsValue in the object
Music + ="
- "+ N [" optionValue "] +"
";
});
Music + ="
";
$ ('# Result'). append (music );
}
});
Return false;
});
});
You can also use the $. getJSON () method to simplify the Code:
The Code is as follows:
$ (Document). ready (function (){
$ ('# Click'). click (function (){
Response .getjson('music.txt ', function (data ){
Var music ="
";
$. Each (data, function (I, n ){
Music + ="
- "+ N [" optionValue "] +"
";
});
Music + ="
";
$ ('# Result'). append (music );
});
Return false;
});
});