首页 文章

用于获取响应的jQuery AJAX语法

提问于
浏览
0

我正在处理一个简单的AJAX请求,该请求在单击按钮时调用URL . 我已经成功运行了基础知识,以便在单击按钮时对URL进行GET请求,并且我已通过检查其他服务器上的日志确认了GET请求 . 这是简单的请求脚本:

< script >
  $("#callContact1").click(function() {

    $.ajax({

      url: "https://www.server.com?type=makecall",
      data: {},
      method: "GET",
      success: function(data) {

      }

    });

  }); <
/script>

我现在正试图在我的html中隐藏div中显示来自GET请求的响应:

<div id="ajaxResponse" class="alert alert-info text-center" role="alert" style="display:none">
  Callback Response
</div>

我修改了脚本如下:

< script >
  $("#callContact1").click(function() {

      $.ajax({

        url: "https://www.server.com?type=makecall",
        data: {},
        method: "GET",
        success: function(data) {
          $('#ajaxResponse').html(data);
          $("#ajaxResponse").show();

        }
      });

      fail(function(xhr) {
          var httpStatus = (xhr.status);
          var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
          console.log('ajaxError: ' + ajaxError);
          //make alert visible
          $('#ajaxResponse').html(ajaxError);
          $("#ajaxResponse").show();
        }

      }); <
    /script>

但我遇到了一些我似乎无法克服的语法错误 . 基本上我想插入来自GET请求的响应,其中包括对成功请求的简单文本响应或遇到错误的错误 .

2 回答

  • 0

    如果使用 .fail() ,则使用 .then() 或jQuery deferred.done() ,可以链接到 .then() . 关闭 </script> 也应在同一行 .

    <script>
      $("#callContact1").click(function() {
            $.ajax({
                url: "https://www.server.com?type=makecall",
                data: {},
                type: "GET"
              })
              .then(function(data) {
                $('#ajaxResponse').html(data).show();
              })
              .fail(function(xhr) {
                  var httpStatus = (xhr.status);
                  var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
                  console.log('ajaxError: ' + ajaxError); 
                  //make alert visible 
                  $('#ajaxResponse').html(ajaxError).show();
             })
        })
    </script>
    
  • 0

    fail 方法未在您的代码中定义 . 您可以使用 deferred done / fail方法附加成功和失败回调:

    <div id="ajaxResponse" class="alert alert-info text-center" role="alert" style="display:none"></div>
    
    <script>
      $("#callContact1").click(function() {
    
      $.ajax({
    
        url: "https://www.server.com?type=makecall",
        data: {},
        method: "GET"
      }).done(function (data) {
          $('#ajaxResponse').html(data);
          $("#ajaxResponse").show();
      }).fail(function (xhr){
          var httpStatus = xhr.status;
          var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
          console.log('ajaxError: ' + ajaxError);
          //make alert visible
          $('#ajaxResponse').html(ajaxError);
          $("#ajaxResponse").show();
      });
    </script>
    

相关问题