AJAX加载消息

时间:2012-11-08 11:11:53

标签: php jquery ajax

我想在通过AJAX检索结果时显示加载消息,但我不能。有人可以帮忙吗?

<script type="text/javascript">

$(function() {

    $(".search_button").click(function() {
        // getting the value that user typed
        var searchString    = $("#search_box").val();
        // forming the queryString
        var data            = 'search='+ searchString;

        // if searchString is not empty
        if(searchString) {
            // ajax call
            $.ajax({
                type: "POST",
                url: "do_search.php",
                data: data,
                beforeSend: function(html) { // this happens before actual call
                    $("#results").html('');
                    $("#search_result_box").show();
                    $("#searchresults").show();
                    $(".word").html(searchString);
               },
               success: function(html){ // this happens after we get results
                    $("#results").show();
                    $("#results").append(html);
              }
            });   
        }
        return false;
    });
});
</script>

2 个答案:

答案 0 :(得分:2)

我会在触发AJAX请求之前更改消息。所以,点击或提​​交时:

<script>
$('form').on('submit', function(e) {
    e.preventDefault();
    $('#response').html('<p>Loading&hellip;</p>');
    $.post($(this).attr('action'), $(this).serialize(), function(response) {
        // do something here with the response
        $('#response').html('<p>Request successful.</p>');
    });
});
</script>

答案 1 :(得分:2)

为什么不使用beforeSend和success方法来显示/隐藏加载消息

beforeSend: function(html) { // this happens before actual call

  // DO SOMEHTING HERE TO SHOW YOUR LOADING MESSAGE AS $('#loading').show();

  $("#results").html('');
  $("#search_result_box").show();
  $("#searchresults").show();
  $(".word").html(searchString);
},
success: function(html){ // this happens after we get results

  // DO SOMEHTING HERE TO HIDE YOUR LOADING MESSAGE AS $('#loading').hide();

  $("#results").show();
  $("#results").append(html);
}

RGDS