简体   繁体   English

如何将事件监听器添加到 xmlhttp ajax 请求

[英]How to add event listener to xmlhttp ajax request

I'm trying to add an event listener to the output I get from my xmlhttp AJAX request, in this example I get a button after a successful ajax request but when I click on the button , the eventlistener I have set does not trigger the 'myfunction()' to show an alert我正在尝试向从我的 xmlhttp AJAX 请求获得的输出中添加一个事件侦听器,在此示例中,我在成功的 ajax 请求后获得一个按钮,但是当我单击该按钮时,我设置的事件侦听器不会触发 ' myfunction()' 显示警报

index.html索引.html

 <div id="list"><p></p></div>

script脚本

function myFunction() {
alert("Hello! I am an alert box!");
}

function getdata() {

    var o = new XMLHttpRequest();
    (o.timeout = 3e4),
        (o.onload = function () {
            document.getElementById("list").innerHTML = this.responseText;
             
            
        }),
        o.open("GET", "view.php", !0),
        (o.ontimeout = function () {
            document.getElementById("list").innerHTML = '<b>Time out, please check your Internet 
 connection or </b><br><input type="button" class="retry" value="RETRY" onclick="getdata()">';
        }),
        o.send(),
        (document.getElementById("list").innerHTML = '<b>FETCHING RESULTS</b><div class="loader"> 
</div>');
    
        
}

}
document.getElementById("mybutton").addEventListener("click", myFunction);

view.php查看.php

<button class="nput" id="mybutton"> click me</button>

Your code is so badly formatted... Here you can find a working example on how to use the XMLHttpRequest events:你的代码格式太糟糕了......在这里你可以找到一个关于如何使用 XMLHttpRequest 事件的工作示例:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/load_event https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/load_event

The Mozilla documentation ( https://developer.mozilla.org ) is an excellent source of knowledge about JavaScript, I would strongly recommend that you look for answers there before asking the community, especially when it comes to basic and common APIs like XMLHttpRequest. Mozilla 文档 ( https://developer.mozilla.org ) 是有关 JavaScript 的绝佳知识来源,我强烈建议您在询问社区之前先在那里寻找答案,尤其是在涉及 XMLHttpRequest 等基本和常见 API 时。

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

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