代码之家  ›  专栏  ›  技术社区  ›  Stanza

使用XmlHttpRequest对象动态引用JQuery

  •  0
  • Stanza  · 技术社区  · 7 年前

    我正在尝试使用xmlhttrequest对象加载jQuery

    我有以下代码:

     loadDoc("https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js", myFunction1);
    
        function loadDoc(url, cFunction) {
          var xhttp;
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              cFunction(this);
            }
          };
          xhttp.open("GET", url, true);
          xhttp.send();
        }
    
        function myFunction1(xhttp) {
          // action goes here
          $(document).ready(function() {
            alert('test');    
        });
    
        } 
    

    我得到了错误:

    (index):62 Uncaught ReferenceError: $ is not defined
        at myFunction1 ((index):62)
        at XMLHttpRequest.xhttp.onreadystatechange ((index):53)
        at loadDoc ((index):57)
        at window.onload ((index):46)
    

    为什么会这样?

    我通常希望这样做,因为我在CRM表单中无法使用。

    1 回复  |  直到 7 年前
        1
  •  0
  •   The scion    7 年前

    试着在这里的控制台上运行这个脚本,你会发现你的代码执行起来没有问题。代码的问题是,您试图在此行中使用Jquery的$符号

    $(文档)。就绪(函数(){

    但是您没有真正初始化页面上的Jquery库,因此javascript无法识别这个符号。

    如果你想在页面中包含Jquery库,你应该像这个问题一样- include jquery