Javascript AJAX 请求 - 检查操作是否成功

标签 javascript jquery html

我有一个从发出 HTTP GET 请求的按钮调用的 Javascript。当它遇到错误时,它会显示一个带有请求错误的隐藏 div,这一切都运行良好。这是脚本:

$("#callContact1").click(function() {
  console.log('starting event');
  $.ajax({
      url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
      data: {},
      type: "GET"
    })
    .then(function(data, status, xhr) {
      $('#ajaxResponse1').html(data).show();
      var httpStatus = status;
      var httpResponseCode = (xhr.status);
      console.log('httpStatus: ' + httpStatus);
      console.log('httpResponseCode: ' + httpResponseCode);
    })
    .fail(function(xhr) {
      var httpStatus = (xhr.status);
      var httpResponseCode = (xhr.getAllResponseHeaders);
      var ajaxError = 'There was an requesting the event. HTTP Status: ' + httpStatus;
      console.log('httpStatus: ' + httpStatus);
      console.log('httpResponseCode: ' + httpResponseCode);
      //make alert visible 
      $('#ajaxResponse1').html(ajaxError).show();
    })
})

我现在需要稍微扩展一下,当成功时,显示一个不同的隐藏 div 和成功消息,例如:

$('#ajaxResponseSuccess1').html('Event Update in Progress').show();

我只是不确定如何扩展这个脚本——此时对于 JS 和 jQuery 来说还是相当新的。

最佳答案

JQuery AJAX中有一个成功函数:

像这样使用它:

.success(function(response) {
   //DO stuff here.
})

更好更简单的代码可以是这样的:

        $.ajax({
            url: 'http://example.com',
            method: 'GET',
            success: function (response) {

            },
            error: function (e) {

            }
        });

查看 JQuery ajax 函数的完整文档位于 http://api.jquery.com/jquery.ajax/

或在

https://www.w3schools.com/jquery/ajax_ajax.asp

关于Javascript AJAX 请求 - 检查操作是否成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44559969/

相关文章:

javascript - 查找最接近的元素并在元素之前插入

javascript - Rxjs操作符switchMap

javascript - 使用 .each 从表创建字符串,如何在每行后添加换行符?

python - 如何在我的网站上将 WMD markdown 语法转换为 HTML?

jquery - 如何点击 iframe 将其删除?

javascript - 使用 jQuery 从数据库访问对象

html - 如何将一个div放在另一个div下面并填充大小?

javascript - 我的导航栏无法点击

javascript - 将 php 代码与 jquery/javascript 结合起来

javascript - Selectize.js如何获取当前选中的输入项的值