跨域动态获取服务信息方式

       最近需要开发一个可以生成放在网站任意地方的动态代码,由于公司网站比较大,所以可能放到的地方与服务端程序不再一个系统,也可能不在同一域名下,根据以前的经验积累和周末总结,我找到两种可行方式。

1.在程序中使用引用服务端js文件,并在js文件中实现使用<script>标签动态加载服务端程序代码

生成的代码动态代码片段

var host_url = 'http://l-save.com/'假设服务器地址是这个

     首先判断是否引入jQuery,没有则加载

if (typeof jQuery == "undefined")
{
    document.write('<script type="text/javascript" src="‘+host_url+‘js/jquery/jquery-1.4.min.js" ><\/script>');
}


<script type="text/javascript" src="‘+host_url+’js/plugin.js" ></script>

<div id="content">内容<input type="hidden" id="pid" value="1" />

</div>

plugin.js代码片段

//判断命名空间是否定义
if (typeof Plugin == undefined)
{
    var Plugin = {};
}

(function($){
    $(document).ready(function() {
       
        Plugin.initData();
    });
    Plugin.initData= function()
    {
        var project_id = $('#pid').val();
        if(project_id)
        {
            if($('#script_info').length == 0)
            {
                $('#content').after('<div id="script_info" ></div>');
            }
            var host = window.location.host;
            var url = 'http://l-save.com/test/plugin.php?pid='+pid+'&h='+host;
            $('#script_info').append('<script src="'+url+'" ></script>');
            //alert($('#script_info').html());
            Plugin.interval = setInterval(function() {
                Plugin.getInfo();
            },100);

          }
    };
   
    
    Plugin.getInfo = function(){
       
        if(typeof result != 'undefined')
            {
              
               console.log(result);
               //更新页面信息
               clearInterval(Plugin.interval);
            }
        
    };
    
})(jQuery);

plugin.php

var host = window.location.host;
var h='<?php echo $_GET['h'];?>';
if(host == h && /[0-9a-z-.]*(focus.cn|sohu.com)/i.test(h)){
<?php
$a = array(array('aid'=>'bj0000012344','title'=>iconv('gbk','utf-8','画好')),
        array('aid'=>'bj00000123555','title'=>'good project'),
        );
$a = json_encode($a);

?>
var result = eval('<?php echo $a;?>');
}
else
{
  alert('访问非法');
}


2. 第二中方式是利用隐藏域表单提交,提交的target设置为一个隐藏的iframe,使用js从iframe获取返回信息,以下代码是参照ajaxfileupload.js改写,还没有测试,有兴趣的同学可以看看,发现这种跨域不行,没有找到解决办法,谁知道???、


jQuery.extend({
    createUploadIframe: function(id)
    {
            var frameId = 'jFrame' + id;
            var io = '<iframe id="' + frameId + '" name="' + frameId + '"  style="display:none;" />';
            jQuery("body").append(io);
            return io;
    },
    createUploadForm: function(id, fileElementId)
    {
        //create form
        var formId = 'jForm' + id;
        var field = 'jField' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" ></form>');

        var i =  0;
        var elementIds = new Array();
        elementIds = fileElementId.split(",");

        for(i; i< elementIds.length;i++){
            var oldElement = $('#' + elementIds[i]);
            var newElement = $(oldElement).clone();
            $(newElement).attr('id', field+i);
            $(newElement).appendTo(form);
        }
        $(form).appendTo('body').hide();
        return form;
    },

    ajaxForm: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime();
        var form = jQuery.createUploadForm(id, s.fileElementId);
        var io = jQuery.createUploadIframe(id);
        var frameId = 'jFrame' + id;
        var formId = 'jForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
        {
            jQuery.event.trigger( "ajaxStart" );
        }
        var requestDone = false;
        // Create the request object
        var xml = {};
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
        {
            var io = document.getElementById(frameId);
            try
            {
                if(io.contentWindow)
                {
                     xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                     xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

                }else if(io.contentDocument)
                {
                     xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            }catch(e)
            {
                jQuery.handleError(s, xml, null, e);
            }
            if ( xml || isTimeout == "timeout")
            {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                    {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );

                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
                                    {    try
                                        {
                                            $(io).remove();
                                            $(form).remove();

                                        } catch(e)
                                        {
                                            jQuery.handleError(s, xml, null, e);
                                        }

                                    }, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 )
        {
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try
        {
           // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if(s.encoding)
            {
                form.encoding = s.encoding;
            }
            $(form).submit();

        } catch(e)
        {
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }
        return {abort: function () {}};

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
            //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})


     


转载于:https://my.oschina.net/u/196016/blog/131864

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值