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

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

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

生成的代码动态代码片断 html

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

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

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


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

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

</div> 服务器

plugin.js代码片断 app

//判断命名空间是否认义
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;     } })

相关文章
相关标签/搜索