2014-04-21 54 views
0

我是JavaScript和JSON的新手,我已經完成了一項任務。請找到JSON在下面的鏈接,從複雜JSON中獲取數據

http://pastebin.com/0BY3eptF

根據我上面是一個非常複雜的JSON。

我想通過ajax

success: function(api) { 
    console.log(api.SearchResult); // trying to fetch information on SearchResult object 
} 

這不起作用獲取從WSDL出來了。我想了解如何迭代每個JSON字符串循環。我也看到一個數組,它是WSResult []。一個整潔的javascript與解釋將幫助我很多。謝謝。

+2

你在javascript知道JSON.parse的?還是看http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript –

+0

謝謝約翰巴薩我之前不知道這個... –

回答

1

一些Web服務返回的內容類型爲純文本,而不是JSON,你必須手動轉換成JSON 。下面的代碼將幫助你做同樣的事情。

 
success: function(api) { 
    if (api.constructor === String) { 
     api = JSON.parse(api); 
    } 
    console.log(api.SearchResult); 
} 

要通過api.SearchResult.Result.WSResult陣列循環,請看下面的代碼

 
$(api.SearchResult.Result.WSResult).each(function (index, val) { 
    // here val is single object of WSResult array 
}); 
+0

或者我相信明確指定具體的數據類型將確保JQuery的處理這一切都爲你.... – vogomatix

+0

@vogomatix是正確的 –

1

success: function(api) {},在這裏,api仍然是一個字符串,你必須首先分析到JSON:

success: function(api) { 
    var api = JSON.parse(api); 
    console.log(api.SearchResult); // trying to fetch information on SearchResult object 
} 
+0

如果你已經設置的dataType這不是一個字符串到AJAX調用中的JSON。它也應該推斷,如果使用jQuery – vogomatix

+0

@vogomatix你是對的。 – wong2

1

不是一個完整的答案,但一些有用的線索:

$ajax({ 
    url: 'http://myURL', 
    // specify the datatype; I think it overrides inferring it from the document MIME type 
    dataType: 'json', 
    success: function (api) { 
     // provided your data does come back as a JSON document 
     // you should be able to access api.SearchResult 
    }, 
    error: function(jsXHR, textStatus, errorThrown) { 
     // always have an error handler, so you can see how it went wrong. 
    } 
); 

閱讀節在這裏dataType,因爲它可能會解決你的問題