【问题标题】:AJAX Get Request ButtonAJAX 获取请求按钮
【发布时间】:2021-01-02 07:30:30
【问题描述】:

我希望在单击按钮时发送一个 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>

【问题讨论】:

    标签: javascript ajax button get xmlhttprequest


    【解决方案1】:

    看到你正在导入 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>
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • (index):1 从源 'ip' 访问 XMLHttpRequest 在 'myurl' 已被 CORS 策略阻止:不存在 'Access-Control-Allow-Origin' 标头请求的资源。 (索引):22 GETmyurl::ERR_FAILED
      • 这是因为 myurl.com 与调用不在同一个域中。您必须调用同一个域或在接收调用的服务器上启用交叉。
      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2011-06-05
      • 2017-08-23
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      相关资源
      最近更新 更多