我试图从json文件中获取响应文本但是能够获得存在响应文本的对象 json数据是:
var response = [{
"id": 1,
"name": "Web Demo"
}, {
"id": 2,
"name": "Audio Countdown"
}, {
"id": 3,
"name": "The Tab Key"
}, {
"id": 4,
"name": "Music Sleep Timer"
}, {
"id": 5,
"name": "Music Sleep Timer"
}];
和jquery Ajax代码如下
var request = $.ajax({
url: "data.json",
type: "GET",
dataType: "application/json"
});
我尝试在请求后保留.responseText但是我无法获得唯一的响应文本如何才能让它能够返回对象
答案 0 :(得分:1)
请你纠正你的json数据格式.....
$(document).ready(function () {
GetLiList();
});
function GetLiList() {
data = '[{"id" : "1", "name" : "Web Demo"},{"id" : "2", "name" : "Audio Countdown"},{"id" : "3", "name" : "The Tab Key"}]';
var response = JSON.parse(data);
var counter = 0;
for (counter = 0; counter <= response.length; counter++) {
$('#users .list').append('<li id="' + response[counter].id + '"><h3 class="name">' + response[counter].name + '</h3></li>')
}
}
&#13;
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div id="users">
<ul class="list"></ul>
</div>
&#13;
答案 1 :(得分:0)
尝试使用getJSON():
$.getJSON( "data.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
答案 2 :(得分:0)
您可以使用jquery的getJSON方法,如下所示,
$.getJSON( "data.json", function( data ) {
// write your logic here.
});
答案 3 :(得分:0)
如果您只想检索文本,请修改contentType。
var request = $.ajax({
url: "data.json",
type: "GET",
dataType: "text/plain"
});