今天要用 Yahoo YUI3 实现查询框的 autocomplete,通过远程方法获取 jsonp 数据,各种查手册google百度,结果连 yui library 里的远程访问例子都没太懂。
现把问题贴在下面
1. 关于例子 Remote Data via JSONP
<div id="demo" class="yui3-skin-sam"> <!-- You need this skin class --> <label for="ac-input">Enter a YUI module name:</label><br> <input id="ac-input" type="text" size="45"> </div> <script> YUI().use('array-extras', 'autocomplete', 'autocomplete-highlighters', function (Y) { function locateModules(response) { var results = (response && response.data && response.data.results) || []; return Y.Array.filter(results, function (result) { return result._type === 'module'; }); } Y.one('#ac-input').plug(Y.Plugin.AutoComplete, { resultHighlighter: 'phraseMatch', resultListLocator: locateModules, resultTextLocator: 'name', source: 'http://yuilibrary.com/api/v1/search/suggest?q={query}&callback={callback}&count=50' }); }); </script>
这里 source 后 url 里用 {query} 和 {callback}什么时候被输入框中的动态变化的字符串代替呢?为什么我访问的 source: 'http://autoc.finance.yahoo.com/autoc?query={query}&callback=YAHOO.Finance.SymbolSuggest.ssCallback' 就不可以
2. 有提示说要用 source: function(query, callback),于是我用如下代码
<script type="text/javascript"> $(document).ready(function(){ YUI().use('autocomplete', function (Y) { function locateModules(response) { var results = (response && response.ResultSet && response.ResultSet.Result) || []; return results; } Y.one('#ac-input').plug(Y.Plugin.AutoComplete, { activateFirstItem: true, resultListLocator: locateModules, resultTextLocator: 'name', source: function (query, callback) { // Use JQuery to call JSONP API var url = 'http://autoc.finance.yahoo.com/autoc?query='+document.getElementById("ac-input").value+'&callback=YAHOO.Finance.SymbolSuggest.ssCallback'; $.get(url,function(data, status){ document.getElementById("topSec").innerHTML=url; // this is for test }); // Implement call back function for Yahoo symbol JSONP API YAHOO.Finance.SymbolSuggest.ssCallback = function (data) { callback(data.ResultSet.Result); } } }); }); }); </script> <body> <div id="queryForm" class="yui3-skin-sam"> <form> <font color="#ffffff" size="4px">Company:</font> <input id="ac-input" type="text" size="80px" style="color:#cccccc;" value="Enter company symbol" onfocus="this.value=''; this.style='color:#000000';" onblur="if(this.value.length < 1) {this.value='Enter company symbol';style='color:#cccccc';}"/> <input type="button" value="Search" onclick=""> </form> </div> </body> </html>
其中 use jquery to call jsonp API 和 implement call back function for Yahoo symbol JSONP API 是任务要求中给的提示
做了一天还是不明白,特别是 YUI 的文档都不太懂,希望各位熟悉的高手答疑解惑。