我有一个 HTML 表单,其中包含查询外部服务的操作。
当我提交表单时,我登陆了外部网站的页面。该网站仅列出 JSON 输出。
有什么方法可以将此对象存储在 JavaScript 变量中吗?
<form action="http://rdio-service.herokuapp.com//search?q=" method="get" target="_top" >
Input artist: <input type="text" name="q"><br>
<button>Find songs</button>
</form>
我听说过 JQuery 方法 $.getJSON
,但它看起来只适用于本地数据。
最佳答案
不使用 jQuery 的跨域 Ajax
OP 询问如何查询以 json 格式返回音乐数据的 Web 服务。然而,Web服务是“外部”的,需要跨域ajax请求。除非得到服务器授权,否则浏览器会阻止这些请求(“访问被拒绝”)。通常,服务器必须设置请求 header “Access-Control-Allow-Origin”,指定允许谁进行查询并提供 jsonp 响应。在这种情况下,似乎没有为其配置 Web 服务。欲了解更多信息,请参阅:MDN HTTP access control (CORS)
解决此问题的一种方法是使用代理服务器。代理代表客户端发出请求。下面的示例将请求发送到 Yahoo YQL它为我们请求数据,然后以 jsonp 格式发送回来。 (雅虎、谷歌和其他公司提供此服务)
运行示例进行测试:
我试图保持这个相当简单来说明该技术。它搜索并显示音乐专辑标题和封面的列表。此外,服务可能需要几秒钟的时间才能响应。
<html>
<body>
<style type="text/css">
#output table { border-collapse: collapse; font-family: sans-serif; font-size: 16px;}
#output td { border: 1px lightgray solid; padding: 2px;}
#output img {height: 100px; width: auto; }
</style>
Enter keywords:
<input id="keyword" type="text" value="Bach"><button onclick="search()">Search...</button>
<div id="output"></div>
<script type="text/javascript">
// jsonp callback
function callback( obj ) {
var i, data, html='';
try {
data = obj.query.results.json.data;
for(i=0; i<data.length; i++) {
html += '<tr><td><img src="' + data[i].icon + '"></td><td>' + data[i].name + '</td></tr>';
}
html = '<table>' + html + '</table>';
}
catch(e) { html = 'No search results.' }
document.getElementById('output').innerHTML = html;
}
// cross-domain ajax via proxy
function search( ) {
var proxy, query, options, keyword, head, script;
keyword = document.getElementById('keyword').value;
keyword = keyword.replace(/\s/g,'+');
proxy = 'https://query.yahooapis.com/v1/public/yql';
query = "?q=" + encodeURIComponent( "select * from json where url='http://rdio-service.herokuapp.com//search?q=" + keyword + "'" );
options = '&diagnostics=true&format=json&callback=callback';
head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
script = document.createElement('script');
script.type = 'text/javascript';
script.src = proxy + query + options;
head.appendChild( script );
}
search( );
</script>
</body>
</html>
该服务返回一个对象数组,例如:
"data": [
{
"object_type": "search_result",
"id": "t4727843",
"name": "Didgeridoo",
"url": "/artist/Duke_Ellington/album/The_Afro-Eurasian_Eclipse_(Remastered)/track/Didgeridoo/",
"length": "32",
"radio_id": "sr4727843",
"type": "track",
"icon": "http://rdio1img-a.akamaihd.net/album/f/b/d/000000000005ddbf/3/square-200.jpg"
},
more records ...
关于javascript - 将表单操作调用的 JSON 输出保存在 JavaScript 变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443172/