Page 83 - JavaScript修炼之道
P. 83

任务32  跨域“Ajax”(方法收集2)              73


                   使用之前那种普通的JSON-P

                   window.jsonpCallback = function jsonpCallback(data) {
                     $('responses').update(data.payload.escapeHTML());
                   };
                   document.documentElement.firstChild.appendChild(
                     new Element('script', { type: 'text/javascript',
                   src: this.href + '?r=' + Math.random() + '&callback=jsonpCallback' }));

                   使用JSON-P-X 形式的YQL html表
                                 ①
                   function yqlCallback(data) {
                     // data.results是匹配元素HTML片段的数组
                   };
                   var url = "http://github.com/languages/Ruby/updated",
                     xpath = "//*[@class='title']",
                     yql = 'select * from html where url="'+url+'" and xpath="'+xpath+'"',
                     data = { q: yql, format: 'xml', callback: 'yqlCallback' };
                   document.documentElement.firstChild.appendChild(
                     new Element('script', { type: 'text/javascript',
                       src: 'http://query.yahooapis.com/v1/public/yql?' +
                         Object.toQueryString(data) + '&r=' + Math.random() }));

                   使用JSON-P形式的YQL htmlpost表

                   function yqlCallback(data) {
                     // data.query.results.postresult.p == 匹配元素内容的数组
                   };
                   var yql = 'use "http://datatables.org/data/htmlpost.xml" as htmlpost;\
                       select * from htmlpost\
                       where url="http://demos.pocketjavascript.com/server/jsonp/postdemo.php"\
                         and postdata="foo=foo&bar=bar" and xpath="//p"',
                       data = { q: yql, format: 'json', callback: 'yqlCallback' };
                   document.documentElement.firstChild.appendChild(
                     new Element('script', { type: 'text/javascript',
                       src: 'http://query.yahooapis.com/v1/public/yql?' +
                         Object.toQueryString(data) + '&r=' + Math.random() }));

                   使用CSSHttpRequest

                   CSSHttpRequest.get(this.href, function(res) {
                     $('responses').insert('<p>' + res.escapeHTML() + '</p>');
                   });

               相关任务

                     任务30
                     任务31
               ——————————
                  ① XML格式的JSON-P。*
   78   79   80   81   82   83   84   85   86   87   88