2011-08-30 68 views
3

我有一个基于jQuery的“ajax引擎”。接收到响应后,我必须在插入页面之前操作响应。但我需要将响应作为一个jQuery对象。 我这样做有:阻止在jQuery中加载(或解析)脚本执行

tmpActualResult = $('<span/>').html(actualResult); 

而此时的jQuery(或浏览器本身?)执行,其包括在响应脚本 - 而正是这一点不应该发生。稍后我将执行脚本手册。

特别

我将:

  1. 解析响应(可以访问所包含的标签/元素)
  2. 插入元素融入到网页(DOM操纵)
  3. 执行可能的脚本(这是收)
在感谢

编辑: 如果有人也感兴趣,我已经通过扩展jQuery.domManip函数创建了一个更通用的解决方案,如第一个答案中的建议。

(function($, oldDomManip) { 
// Override the core domManip function 
$.fn.domManip = function() { 

    function evalScript(i, elem) { 
     jQuery.globalEval(elem.text || elem.textContent || elem.innerHTML || ""); 
    } 

    var scripts = []; 
    // let jQuery build the fragments 
    var results = jQuery.buildFragment(arguments[0], this, scripts); 
    // change parameter to created fragments 
    arguments[0] = results.fragment.childNodes; 
    // do what jQuery will do - without scripts 
    oldDomManip.apply(this, arguments); 
    if (scripts.length) { 
     // if connection is active 
     if (jQuery.active != 0) { 
      $(this).bind("ajaxStop.scriptCache", function() { 
       $.each(scripts, evalScript); 
       $(this).unbind("ajaxStop.scriptCache"); 
      }); 
     } else 
      $.each(scripts, evalScript); 
    } 
    return this; 
}; 
})(jQuery, jQuery.fn.domManip); 

在ajax请求完成之前它不会执行脚本。为我工作。

+0

究竟是什么反应? –

+0

此时一个简单的HTML字符串。 (有可能的脚本标签) – chuem

回答

3

您不能阻止脚本执行脚本,这些脚本是您尝试使用.html()或.append()添加的标记字符串的一部分。至少不是没有扩展jQuery的domManip功能。它提取所有使用.html()或.append()添加的HTML标记中的脚本并对其进行处理。

但是,您可以自己从字符串中提取脚本标记及其内部文本(js),只需通过.html()或.append()添加标记,然后在需要时自行评估脚本。

+0

好的谢谢 - 至少有可能获得脚本? like:$('').append(response).find(“script”); – chuem

+0

在将响应放入DOM(使用.append()函数)之前,您必须从响应中获取脚本。 – gislikonrad

+0

非常感谢,我将尝试扩展domManip函数,我需要更全面的解决方案。 – chuem

1

试试这个:

var container = document.createElement('div'); 
container.innerHTML = "<div> i am html with script tag <script type="text/javascript">alert('Script executed');</script>end</div>" 
$(container).doSomething()