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. 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:
Copy codeThe 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:
Copy codeThe Code is as follows:
<Div> click the button to obtain JSON data </div>
<Input type = "button" id = "button" value = "OK"/>
<Div id = "result"> </div>
JQuery code for retrieving JSON Data Using Ajax:
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Click'). click (function (){
$. Ajax ({
Type: "GET ",
Url: "music.txt ",
DataType: "json ",
Success: function (data ){
Var music = "<ul> ";
// 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 + = "<li>" + n ["optionValue"] + "</li> ";
});
Music + = "</ul> ";
$ ('# Result'). append (music );
}
});
Return false;
});
});
You can also use the $. getJSON () method to simplify the Code:
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Click'). click (function (){
Response .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;
});
});