Sample Code for getting data in JSON format using Ajax in jQuery _ jquery

Source: Internet
Author: User
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;
});
});
Related Article

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.