我一直在嘗試一些代碼從這裏實現我的目標,但我還沒有找到解決方案。使用JavaScript獲取JSON數組獲取使用javascript(jquery)
目標:我必須使用GET方法從網頁(通過URL)獲取JSON對象數組。我必須用Javascript或HTML來做到這一點。我一直在嘗試JavaScript與jQuery和Ajax。這個想法是當我正在加載的網頁我必須得到JSON對象數組。我想要保存JSON objets數組在字符串中進行操作。 JSON陣列的
的例子,我有一個從http://www.example.com/example
[
{
"type": "1",
"id": "50a92047a88d8",
"title": "Real Madrid"
},
{
"type": "1",
"id": "500cbb1a5ef23",
"title": "Fernando Alonso"
}
]
得到當我在瀏覽器中,我總是得不到迴應我的代碼運行。
這些都是一些代碼片段我已經試過:
HTML代碼
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link type = "text/css" rel = "stylesheet" href = "stylesheet.css"/>
</head>
<body onload = "httpGet('http://www.example.com/example')">
</body>
</html>
Javascript代碼
function httpGet(theUrl)
{
$.getJSON(theUrl, function(data)
{
$.each(data, function()
{
console.log(this['title']);
})
});
}
其他JavaScript代碼
$.ajax(
{
url: theUrl,
type: 'GET',
dataType: 'json',
accept: 'application/json',
success: function(data)
{
console.log(data);
var objets= $.parseJSON(data);
$.each(objets, function(i, obj)
{
console.log(obj.title);
});
}
});
而且我有證明一下t代碼從這裏(樁溢出)...
非常感謝你和我的英語原諒。
編輯:
前段時間我試着用字符串化,但我真的不知道怎麼能工作。 我證明了如下:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, true); // I tried with true and with false
xmlHttp.send();
var answer= xmlHttp.responseText;
var str = JSON.stringify(answer);
console.log(str);
var jsonResponse = JSON.parse(str);
console.log(jsonResponse);
}
是指定的URL指向_your_域,即同一個域中從加載你的頁面?標準的ajax請求(對於JSON或任何其他格式)不能跨域使用。 – nnnnnn
爲此使用stringify –
那麼成功時'數據'中有什麼?它是否成功?也許它會碰到'error'。您是否嘗試添加回調並查看會發生什麼?另外,在Chrome/Firefox Inspector中檢查您的網絡標籤通常也有幫助。 – Bartek