且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery未在Ajax请求的脚本标记中加载js文件

更新时间:2023-12-05 08:47:58

这是jQuery的正常行为,如果要包含脚本,则需要解析html并手动添加它们.

That's jQuery's normal behaviour, if you want to include your scripts, you need to parse the html and add them manually.

坏消息:您甚至无法使用$() ...选择字符串中的script标签...

Bad news: you can't even select script tags in strings with $()...

我没有对此进行测试,但是这个快速而肮脏的示例应该可以工作:

I didn't test that, but this quick and dirty example should work:

function createGetScriptCallback(url) {
  return function () {
    return $.getScript(url);
  }
}
$.ajax({
  type: 'POST',
  dataType: 'xml/html',
  cache: false,
  url: "/html/with/scripttags",
  data: {
    somedata: 'value'
  },
  success: function (data) {
    var parser, doc, scriptsEl, callbacks;
    parser = new DomParser();
    doc = parser.parseFromString(data, "text/html")
    scriptsEl = doc.querySelectorAll("script[src]");
    callbacks = []
    for (var i = 0; i < scriptsEl.length; i++) {
      callbacks.push(createGetScriptCallback(scriptsEl[i].getAttribute("src")));
    }
    $.when.apply($, callbacks)
      .fail(function (xhr, status, err) {
        console.error(status, err);
      });
    $('body').append(data);
  }
});

但是您不应该依赖html来加载脚本.

But you should not depend on the html to load your scripts.

编辑:更少的脏代码(受@ guest271314的回答启发)

edit: less dirty code (inspired by @guest271314 's answer)