0

我想在通过 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>
4

2 回答 2

2

Why not using beforeSend and success methods to show/hide a loading message

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

于 2012-11-08T11:20:18.290 回答
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>
于 2012-11-08T11:15:50.813 回答