2016-04-21 155 views
2

當我打電話的api,在json格式(標題和內容)返回一個隨機的報價,我收到json就好:用JavaScript解析JSON失敗

ajax({ url: 'quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', type: 'json' }, 
function(data) { 
console.log((JSON.stringify(data))); 
console.log(data.content); 

console.log((JSON.stringify(data))); 

輸出:

[{ 
    "ID":1562, 
    "title":"Michael Bierut", 
    "content":"Most of the mediocre design today comes from designers who are faithfully doing as they were taught in school: they worship at the altar of the visual.\n", 
    "link":"http:\/\/quotesondesign.com\/michael-bierut-3\/", 
    "custom_meta":{"Source":"article"} 
}] 

但是console.log(data.content);輸出:無。

+1

根JSON值不具有' 「內容」'屬性來匹配'data.content'。它看起來'data'是一個數組--' console.log(data [0] .content)'等等([Access/process(nested)objects,arrays or JSON](http://stackoverflow.com/questions/) 11922383/access-process-nested-objects-arrays-or-json)) –

+0

@RayonDabre目前還不清楚這是jQuery。儘管有一些相似之處,但這些參數似乎與'jQuery.ajax()'不兼容。 –

+0

@JonathanLonowski,真的! – Rayon

回答

2

嘗試console.log(data [0] .content);

1

我認爲問題是,你是不是字符串化的解析

console.log(JSON.parse(data));

編輯:關於這個問題 的例子有一些其他的問題。這裏是一個正確格式化AJAX請求:

$.ajax({ 
    type: 'GET', 
    dataType: 'json', 
    url: 'URL_HERE', 
    success: function(data) { 
    console.log(data.content); 
    } 
}); 

和一個工作示例https://jsfiddle.net/1fjqgajk/8/

+0

我做的ajax請求是基於卵石的,我做的方式是建議做的方式。 –

0
$.ajax({url:"quotesondesign.com/wp-json/posts? filter[orderby]=rand&filter[posts_per_page]=1",type:'POST',dataType="json",success: function(data){ 
// if you dont wanto to use dataType use eval; 
//var jsonObj=eval(data) 

}});