Javascript AJAX获取请求按钮

Javascript AJAX获取请求按钮,javascript,ajax,button,get,xmlhttprequest,Javascript,Ajax,Button,Get,Xmlhttprequest,我想在单击按钮时发送GET请求,但我不知道如何将AJAX脚本与按钮连接起来 变量url=”http://myurl.com"; var xhr=new XMLHttpRequest(); xhr.open(“GET”,url); xhr.onreadystatechange=函数(){ if(xhr.readyState==4){ 控制台日志(xhr.status); console.log(xhr.responseText); }}; xhr.send(); 发出请求您需要将其转换为函

我想在单击按钮时发送GET请求,但我不知道如何将AJAX脚本与按钮连接起来


变量url=”http://myurl.com";
var xhr=new XMLHttpRequest();
xhr.open(“GET”,url);
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
控制台日志(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();


发出请求
您需要将其转换为函数并通过按钮调用:

<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>

函数调用()
{
变量url=”http://myurl.com";
var xhr=new XMLHttpRequest();
xhr.open(“GET”,url);
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
控制台日志(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
提出请求

在导入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>

提出请求
$(“按钮”)。单击(函数(){
$.get(”http://myurl.com,函数(结果){
控制台日志(结果);
});
});

(索引):1 CORS策略已阻止从源站“”访问“”处的XMLHttpRequest:请求的资源上不存在“访问控制允许源站”标头。(索引):22 GETmyurl::ERR_失败这是因为myurl.com与调用不在同一域中。您必须对同一域进行呼叫,或在接收呼叫的服务器上启用交叉。