jQuery ajax请求代码实例分享

我心飞翔 分类:实例代码

关于jQuery的ajax请求的具体概念什么的这里就不多介绍了。下面就分享极端关于应用的相关实例代码。

代码实例一:

$.ajax('/ROUTE', {
  type: 'GET'
  data: {param1: 'Hello', param2: 'World'},
  dataType: 'json',
  contentType: 'application/json',
  timeout: 3000,
  success: function(response) {
    // console.log(response.something);
  },
  error: function(request, errorType, errorMessage) {
    // console.log("[" + errorType + "] " + errorMessage);
  },
  beforeSend: function() {
    // do something like .addClass('is-fetching')
  },
  complete: function() {
    // do something like removeClass('is-fetching')
  }
});

实例代码二:

$.get('/ROUTE', function(response) {
  // success (response: HTML)
});
   
$.getJSON('/ROUTE', function(response) {
  // success (response: JSON)
});

实例代码三:

$('form').on('submit', function(event) {
  event.preventDefault();
  var formData = $(this).serialize();
  $.ajax($(this).attr('action'), {
    type: $(this).attr('method'),
    data: formData,
    dataType: 'json',
    contentType: 'application/json',
    success: function(response) {},
    error: function(request, errorType, errorMessage) {},
    beforeSend: function() {},
    complete: function() {},
    timeout: 3000
  });
});

回复

我来回复
  • 暂无回复内容