Home > Web Front-end > JS Tutorial > body text

Sample code for using Ajax to obtain JSON format data in jQuery_jquery

WBOY
Release: 2016-05-16 17:12:20
Original
994 people have browsed it

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, which can be achieved using Ajax or the $.getJSON() method in jQuery.

The following uses jQuery to read the JSON data format information in the music.txt file.
First, the content in music.txt is as follows:

Copy the code 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:
Copy the code The code is as follows:

Click the button to get JSON data




jQuery code to get JSON data using Ajax:
Copy code The code is as follows:

$(document).ready(function(){
$ ('#button').click(function(){
$.ajax({
type: "GET",
url: "music.txt",
dataType: "json",
success:function(data){
var music="
    ";
    //i represents the index position in data, n represents the object containing the information
    $.each (data,function(i,n){
    //Get the value of the object whose attribute is optionsValue
    music ="
  • " n["optionValue"] "
  • ";
    });
    music ="
";
$('#result').append(music);
}
});
return false;
});
});

Of course, you can also use the $.getJSON() method, the code is simpler:
Copy code The code is as follows:

$(document).ready(function(){
$('#button').click(function( ){
$.getJSON('music.txt',function(data){
var music="
    ";
    $.each(data,function(i,n){
    music ="
  • " n["optionValue"] "
  • ";
    });
    music ="
";
$('# result').append(music);
});
return false;
});
});
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template