我一直在尝试一些代码从这里实现我的目标,但我还没有找到解决方案。使用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