我正在尝试使用 livestream 非常有用的移动 API(位于 http://www.livestream.com/userguide/?title=Mobile_API#Requesting_a_mobile_stream)发出 xml 请求。我感兴趣的是 isLive 响应值。我正在尝试使用这样的 ajax 请求
$.ajax({
type: "GET",
url: "http://xproshowcasex.channel-api.livestream-api.com/2.0/getstream",
datatype: "xml",
success: function(xml){
//this is where I need help. This is what I would like to happen
if (isLive == true) {
//perform action
}
else {
//perform other action
}
我正在使用 http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/ 中找到的插件发出跨域 xml 请求。谁能告诉我这是否是实现这一目标的最有效方法?我还没能让它发挥作用。当我运行 console.log(xml) (这可能不正确)时,JS 控制台显示 objectObject,我认为这意味着我需要解析数据?如果有人能花时间解释这一点,我会很高兴。非常感谢。
最佳答案
你已经很接近了,你链接到的帖子基本上描述了使用跨域请求进行页面抓取,该请求经过 YQL (您可以查看源代码以了解到底发生了什么)。您可以删除该插件并使用 jQuery 通过常规 JSONP 请求完成相同的操作:
function getCrossDomainJson(url, callback) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?callback=?",
data: {
q: 'select * from xml where url="' + url + '"',
format: "json"
},
dataType: "jsonp",
success: callback
});
}
基本上这个函数的作用是调用 Yahoo 的查询 api 并运行一个查询。当响应返回时,返回的脚本将调用 jQuery 提供的回调函数(这就是 JSONP 成为可能的原因)。
query you're using (在 q
参数中指定)针对 XML feed,因此您需要使用 select * from xml
来检索数据。然后,您可以告诉 Yahoo 以 JSON 格式提供结果(我建议使用此格式而不是 XML;XML 是命名空间的)。
现在,当您调用此函数时:
getCrossDomainJson("http://xproshowcasex.channel-api.livestream-api.com/2.0/getstream", function(data) {
// data is in JSON format:
// make sure you can access the isLive property
if (data && data.query && data.query.results && data.query.results.channel) {
alert(data.query.results.channel.isLive);
}
});
回调函数接收通过 YQL 检索的 JSON 数据并查找 isLive
属性。
关于jquery - 有人可以帮我使用 livestream 的 api 发出跨域 xml 请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020357/