【发布时间】:2011-03-11 13:37:20
【问题描述】:
有谁知道我如何使用 $.getJSON 从数组“article”中访问“name”、“url”、“headline”、“timestamp”和“excerpt”?
【问题讨论】:
有谁知道我如何使用 $.getJSON 从数组“article”中访问“name”、“url”、“headline”、“timestamp”和“excerpt”?
【问题讨论】:
daylife.com 似乎没有提供“jsonp”作为返回类型。这意味着脚本标签正文中的 javascript 对象将导致浏览器出错。因此,据我所知,您将无法获取该脚本标签中的数据。
如果他们确实支持 jsonp,他们会查看该回调 url 并返回如下内容:
<script src="your API call here">
callbackFunction({response:"ok", data:[1,2,3]}) //this passes the data to callbackFunction
</script>
他们返回的是这个:
<script src="your API call here">
{response:"ok", data:[1,2,3]} //this is a parse error for the browser
</script>
一种解决方法是通过您的服务器将调用代理到他们的服务器。下面是如何完成它的 C# 示例。 ProxyHandler 方法只是为了说明如何从某些 Web 框架中使用 ProxyJsonpRequest。它没有一个特定的想法。这个想法是javascript客户端将传递一个参数,该参数指定服务器应向其请求数据的远程url。服务器发出该请求并将该数据返回给客户端。下面的代码也只适用于 GET 请求。
public string ProxyJsonpRequest(string remoteServer)
{
HttpWebRequest req = HttpWebRequest.Create(remoteServer) as HttpWebRequest;
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
return new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
public void ProxyHandler()
{
string remote = this.Request.Params["url"];
return new Response(data:ProxyJsonpRequest(remote), ContentType:"text/javascript");
}
【讨论】:
嗯,JSON 文本只包含一个大的 ol' javascript 对象 - 这就是为什么它被称为“JavaScript Object Notation”,因此您可以使用它的限定名称获取任何属性(如 object.property)。读取 JSON 响应,假设您想要获取“article”数组中每个对象的“name”、“url”、“headline”、“timestamp”和“excerpt”:
$.getJSON("http://freeapi.daylife.com/jsonrest/publicapi/4.8/topic_getRelatedArticles?topic_id=&name=business&start_time=2010-06-26&end_time=2010-07-03&sort=date&offset=&limit=10&source_filter_id=&include_scores=&include_image=&include_redundant=&accesskey=b030265d4c2b33652b6d519a10d0a6f0&signature=c683ddf5dee41d321b673fb1413f1f5c&callback=?", function(data){
$.each(data.response.payload.article, function(index, value){
alert("The name: "+ value.source.name);
alert("The url: "+ value.source.url);
alert("The headline: "+ value.headline);
alert("The timestamp: "+ value.timestamp);
alert("The excerpt: "+ value.excerpt);
});
});
请注意查询字符串中的 callback 参数,如果您要在日常生活之外的任何域中使用此代码,这是一个必须 .com,因为大多数浏览器强制执行的同源策略不会让您进行这样的调用,因为将javascript代码从一个页面注入另一个页面是一件可怕而危险的事情,所以您使用回调参数告诉浏览器“放轻松,我知道我在这里做什么”
希望对你有帮助!
【讨论】: