简体   繁体   English

如果动态加载jQuery,则jQuery的ajax()无法正常工作

[英]jQuery's ajax() does not work if jQuery is loaded dynamically

I am trying to use jQuery's post() and get() but they are not working . 我正在尝试使用jQuery的post()get()但是它们不起作用 I do not have HTML so I am loading jQuery this way: 我没有HTML,所以我以这种方式加载jQuery:

var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';
document.head.appendChild(script);

Seems like it is successfully loaded. 好像已成功加载。 Checked using window.jQuery in the console. 在控制台中使用window.jQuery检查。

Right after I create a button: 在创建按钮之后:

var btn = document.createElement("button");
btn.id = 'gogogo';
var txt = document.createTextNode("Go");
btn.appendChild(txt);
document.body.insertBefore(btn, document.body.childNodes[0]);

Button successfully created. 按钮创建成功。

Right after this I have the desired post() : 在此之后,我便有了所需的post()

$("#gogogo").click(function () {
    var txt = '123';
    $.post("/users", {qwe: txt}, function(result){
            alert(result);
    });
});

But nothing happens at all. 但是什么也没有发生 NET section in FireBug remains empty while clicking on the button. 单击按钮时,FireBug中的NET部分保持空白。

Somebody knows what I am doing wrong? 有人知道我做错了吗?

Use .on event of jQuery, As you are dynamically creating element ie event delegation. 使用jQuery的.on事件,当您动态创建元素即event delegation.

For ex. 对于前。

$(document).on("click","#gogogo",function () {
    alert("Inside #gogogo event handler");
    var txt = '123';
    $.post("/users", {qwe: txt}, function(result){
            alert(result);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM