表单提交后加载Ajax

时间:2015-10-21 00:46:49

标签: javascript jquery ajax

我想在提交表单后显示加载图片。这是我目前的代码(我正在使用Bootstrap):

<form method="GET" action="/search/results" id="searchform">
        <div class="form-inline">
        <div class="form-group">
            <input type="text" class="form-control" id="name" name="name" placeholder="Search" style="min-width: 300px;" required autofocus>
        </div>
        <button type="submit" class="btn btn-dark btn-md">Search</button>
        </div>
        <br>
        <div class="form-group">
            <h4 class="text-muted">Scoring Type</h4>
            <label class="radio-inline">
                <input type="radio" name="scoring" id="standard" value="standard" checked> Standard
            </label>
            <!-- other radio options -->
        </div>
</form>
<br>
<div class="modal">
</div>
<style>
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
            background: rgba( 255, 255, 255, .8 ) 
                        url("{% static 'img/loading.gif' %}") 
                        50% 50% 
                        no-repeat;
            }
        body.loading {
            overflow: hidden;   
        }
        body.loading .modal {
            display: block;
        }
</style>

表单提交到名为/ search / results的页面,但我希望此页面加载ajax。加载完成后,我想用包含结果的网页完全替换搜索网页。当它正在加载时,我希望应用$('body').addClass('loading');,这将以我想要的方式显示加载图标(我不希望css中的任何更改,它按照我想要的方式工作)。我到处都看了,但我似乎无法找到适合我的解决方案。感谢。

2 个答案:

答案 0 :(得分:1)

要确保表单不会像往常一样提交: 删除 method="GET";

 <form action="/search/results" id="searchform">

JS:

$("#searchform").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get some values from elements on the page: */
  var $form = $( this );
  var url = $form.attr( "action" );
  //before send
  $("body").addClass("loading");

  /* Send the data using post */
  var posting = $.post(url , $( "#searchform" ).serialize() );

  /* Alerts the results */
  posting.done(function( data ) {
     //use data
     $("body").removeClass("loading");

  });
});

答案 1 :(得分:1)

使用以下程序:

var data = $("#searchform").serialize();

$('#searchform').on('submit',function(event){
event.preventDefault();
$.ajax({
            type: "POST",
            url: "/search/results",
            data: data,
            dataType: "json",
            success: function(data) {
               //on success remove the image
            },
            error: function(){
                  alert('error handing here');
            }
        });
})