跨域動態獲取服務信息方式

       最近須要開發一個能夠生成放在網站任意地方的動態代碼,因爲公司網站比較大,因此可能放到的地方與服務端程序再也不一個系統,也可能不在同一域名下,根據之前的經驗積累和週末總結,我找到兩種可行方式。 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;     } })

相關文章
相關標籤/搜索