Using Ajax in jquery to get JSON format Data sample code _jquery

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