【发布时间】:2013-08-23 18:23:36
【问题描述】:
我一直在尝试这里的一些代码来实现我的目标,但我还没有找到解决方案。
目标:我必须使用 GET 方法从网络(通过 URL)获取 JSON 对象数组。我必须在 Javascript 或 HTML 中做到这一点。我一直在尝试使用 jquery 和 ajax 使用 javascript。这个想法是当我正在加载的网页时,我必须获取 JSON 对象数组。我想将获取的 JSON 对象数组保存在一个字符串中以对其进行操作。
我必须从 http://www.example.com/example 获取的 JSON 数组示例
[
{
"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);
});
}
});
我已经从这里证明了很多代码(stak 溢出)...
非常感谢,请原谅我的英语。
编辑:
前段时间我尝试过使用 stringify,但我真的不知道它是如何工作的。 我证明了以下几点:
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 或任何其他格式)不会跨域工作。
-
为此使用字符串化
-
那么成功后
data中的内容是什么?它有没有打到success。也许它会改为error。您是否尝试为此添加回调并查看会发生什么?此外,在 Chrome/Firefox Inspector 中检查您的网络选项卡通常也会对此有所帮助。 -
URL 没有指向我的域,所以我必须拒绝使用 ajax 请求吗?
-
是的,我尝试过使用回调函数。我总是看到使用 Firebug Firefox 补充执行我的代码的结果。
标签: javascript jquery http-get arrays