Home  >  Article  >  Web Front-end  >  Sample code for using Ajax to obtain JSON format data in jQuery_jquery

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

WBOY
WBOYOriginal
2016-05-16 17:12:20984browse

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