Sample Code for getting JSON format data using Ajax in jQuery

Source: Internet
Author: User

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;
});
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.