如何使用Ajax并在另一个URL上发布数据请求?

时间:2018-12-04 07:37:35

标签: ajax

如何使用Ajax并在另一个URL上发布数据请求? 解决ajax问题

$.ajax({
      type: 'POST',
      url: 'https://kyleschaeffer.com/feed/',
      data: { postVar1: 'theValue1', postVar2: 'theValue2' },
      beforeSend:function(){
        // this is where we append a loading image
        $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
      },
      success:function(data){});
    });

1 个答案:

答案 0 :(得分:0)

从某种意义上说,此jQuery功能非常完美,它可以处理您将需要进行的所有AJAX请求中的99%,它包含成功和失败功能,以确保用户获得所需的正确反馈,并且在处理请求以进行引导时,您会看到旋转的加载映像。

$.ajax({
  type: 'POST',
  url: 'https://kyleschaeffer.com/feed/',
  data: { postVar1: 'theValue1', postVar2: 'theValue2' },
  beforeSend:function(){
    // this is where we append a loading image
    $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
  },
  success:function(data){
    // successful request; do something with the data
    $('#ajax-panel').empty();
    $(data).find('item').each(function(i){
      $('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
    });
  },
  error:function(){
    // failed request; give feedback to user
    $('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
  }
});