简体   繁体   English

AJAX 获取请求按钮

[英]AJAX Get Request Button

I want when I click the button a GET Request to send but I don't know how to connect the AJAX script with the button.我想要当我单击按钮时发送 GET 请求,但我不知道如何将 AJAX 脚本与按钮连接。

 <script> var url = "http://myurl.com"; var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { console.log(xhr.status); console.log(xhr.responseText); }}; xhr.send(); </script>
 <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <button>Make a request</button>

you need transform it in a function and call by the button:您需要将其转换为函数并通过按钮调用:

<script>
    function call()
    {
        var url = "http://myurl.com";
        
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        
        xhr.onreadystatechange = function () {
           if (xhr.readyState === 4) {
              console.log(xhr.status);
              console.log(xhr.responseText);
           }};
        
        xhr.send();     
    }
    </script>

<head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button onclick="call();">Make a request</button>

Seeing as you are importing Jquery, there is also a helper function to fetch data from an AJAX request, you can use it like this:在您导入 Jquery 时,还有一个辅助函数可以从 AJAX 请求中获取数据,您可以像这样使用它:

<head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
<!-- Javascript -->
<script>
$('button').click(function(){
    $.get("http://myurl.com", function(result) {
        console.log(result);
    });
});

</script>

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

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