使用js实现跨域调用bing搜索资源,解决同源策略问题

288 查看


function getDOM(id) {
        return document.getElementById(id)  document;
    }
    function bindEvent (id, event, fn) {
        var getId = getDOM(id);
        if(getId.attachEvent) {
            getId.attachEvent('on' + event, fn);
        } else if(getId.addEventListener) {
            getId.addEventListener(event, fn, false);
        }
    }
var jsonpCallback = function (d) {
        //处理传回数据
        var d = d.AS.Results[0].Suggests;
        var html = '';
        for(var i = 0; i < d.length; i++) {
            html += '<li>' + d[i].Txt + '</li>';
        }
        getDOM('search_result').innerHTML = html;
    }

    //动态创建script,因其带src属性可以实现跨域,不受同源策略的影响,所以使用其获得数据
    function jcallback(searchText) {
        // type=cb&cb=jsonpCallback,实现jsonp数据格式通过封装在函数jsonpCallback中把
        // 数据传回.如果不加 type=cb 浏览器认为是json数据格式传回的,不支持!!
        var url = "http://api.bing.com/qsonhs.aspx?type=cb&cb=jsonpCallback&q=" + searchText + "";
        var script = document.createElement('script');
        script.setAttribute('src', url);
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    //绑定输入事件
    bindEvent('search_txt', 'keyup', function() {
        var searchText = getDOM('search_txt').value;
        //触发事件调用函数
        jcallback(searchText);
        var el = getDOM('search_box');
        var search_list = getDOM('search_list');
        search_list.style.left = getOffsetLeft(el) + 'px';
        search_list.style.top = getOffsetTop(el) + 39 + 'px';
        search_list.style.position = 'absolute';
        search_list.style.display = 'block';
    });

bindEvent(document, 'click', function () {
        getDOM('search_list').style.display = 'none';
    });

    //定义代理函数
    var delegateEvent = function (target, event, fn) {
        bindEvent(document, event, function (e) {
            if(e.target.nodeName == target.toUpperCase()) {
                fn.call(e.target);
            }
        });
    };
    //js代理,实现点击选项跳转页面
    delegateEvent('li', 'click', function () {
        var keyword = this.innerHTML;
        location.href = 'http://cn.bing.com/search?q=' + keyword;
    })