html按钮在ajax调用之前导致回发

时间:2016-09-23 22:34:56

标签: jquery html ajax

我认为这是一个相当标准的HTML表单,用于发送"预订"电子邮件,坐在弹出窗口内。在提交时,我希望通过AJAX将表单数据发送到ashx处理程序(为了存储预订并发送电子邮件),但是按钮会在处理ajax之前导致回发,并且我可以'似乎找到了解决办法。

HTML

<div id="popup1" class="overlay">
            <div class="popup">
              <h2>Book a Table:</h2>
              <a class="close" href="#">
                <i class="pe-7s-close"></i>
              </a>
              <div class="content">
                <form id="booking_form" method="post" action="Bookings.ashx">
                  <div class="form-section">
                    <div>
                      <label>Booking Name:</label>
                      <div>
                        <input type="text" id="input_name" name="name" data-id="id-name" value="" required="true"/>
                      </div>
                    </div>
                    <div>
                      <label>E-mail:</label>
                      <div>
                        <input type="email" id="input_email" name="email" data-id="id-email" size="30" value="" required="true"/>
                      </div>
                    </div>
                    <div>
                      <label>Phone:</label>
                      <div>
                        <input type="text" data-type="input-textbox" id="input_phone" name="phone" data-id="id-phone" size="20" value="" maxlength="100" required="true"/>
                      </div>
                    </div>
                    <div>
                      <label>Number of Guests:</label>
                      <div>
                        <input type="text" data-type="input-textbox" id="input_guests" name="guests" data-id="id-guests" size="3" value="" maxlength="100" required="true"/>
                      </div>
                    </div>
                    <div>
                      <label>Date:</label>
                      <div>
                        <input type="text" id="datepicker" required="true" name="date" data-id="id-date"/>
                      </div>
                    </div>
                    <div>
                      <label>Time:</label>
                      <div>
                        <select class="form-dropdown" style="width:150px" id="time" data-id="id-time[]" required="true">
                          <option value="">  </option>
                          <option value="11:30 am"> 11:30 am </option>
                          <option value="12:00 pm"> 12:00 pm </option>
                          <option value="12:30 pm"> 12:30 pm </option>
                          <option value="1:00 pm"> 1:00 pm </option>
                          <option value="1:30 pm"> 1:30 pm </option>
                          <option value="closed"> </option>
                          <option value="5:00 pm"> 5:00 pm </option>
                          <option value="5:30 pm"> 5:30 pm </option>
                          <option value="6:00 pm"> 6:00 pm </option>
                          <option value="6:30 pm"> 6:30 pm </option>
                          <option value="7:00 pm"> 7:00 pm </option>
                          <option value="7:30 pm"> 7:30 pm </option>
                          <option value="8:00 pm"> 8:00 pm </option>
                          <option value="8:30 pm"> 8:30 pm </option>
                        </select>
                      </div>
                    </div>
                    <div>
                      <label> Any Special Request? </label>
                      <div>
                        <textarea id="input_notes" cols="40" name="notes" data-id="id-notes" rows="5"></textarea>
                      </div>
                    </div>
                    <div class="form-line">
                      <div>
                        <div>
                          <button type="submit">
                            Book Now
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>

JS / AJAX

$(function () {
    // Get the form.
    var form = $('#booking_form');

    // Set up an event listener for the contact form.
    $(form).submit(function (event) {
        // Stop the browser from submitting the form.
        event.preventDefault();

        // Serialize the form data.
        var formData = $(form).serialize();
        var querystring = "";
        querystring += "&name=" + $('input[name=name]').attr('data-id');
        querystring += "&email=" + $('input[name=email]').attr('data-id');
        querystring += "&phone=" + $('input[name=phone]').attr('data-id');
        querystring += "&guests=" + $('input[name=guests]').attr('data-id');
        querystring += "&date=" + $('input[name=date]').attr('data-id');
        querystring += "&time=" + $('input[name=time]').attr('data-id');
        querystring += "&notes=" + $('input[name=notes]').attr('data-id');
        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('Bookings.ashx?method=ProcessRequest&'+querystring),
            data: formData
        }).done(function (response) {

            // Clear the form.
            $('#input_name').val('');
            $('#input_email').val('');
            $('#input_phone').val('');
            $('#input_guests').val('');
            $('#datepicker').val('');
            $('#time').val('');
            $('#input_notes').val('');
        }).fail(function (data) {

            return false;
        });
    });
});

ASHX

public class Bookings : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
        SqlConnection con;
        SqlCommand cmd = new SqlCommand();
        string name = Request["name"].ToString();
        string email = Request["email"].ToString();
        string phone = Request["phone"].ToString();
        Int32 guests = Int32.Parse(Request["guests"].ToString());
        DateTime date = DateTime.Parse(Request["date"].ToString());
        string time = Request["time"].ToString();
        string notes = Request["notes"].ToString();

        con = new SqlConnection(ConfigurationManager.AppSettings["dbConn"]);
        cmd = new SqlCommand("dbo.AddBooking", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("Name", name);
        cmd.Parameters.Add("Email", email);
        cmd.Parameters.Add("Phone", phone);
        cmd.Parameters.Add("Guests", guests);
        cmd.Parameters.Add("Date", date);
        cmd.Parameters.Add("Time", time);
        if (notes.Length == 0)
        {
        cmd.Parameters.Add("Notes",null);
        }
        else { 
        cmd.Parameters.Add("Notes", notes);
        }
        con.Open();
        cmd.ExecuteNonQuery();
        Int32 bookNo = 0;
        cmd = new SqlCommand("dbo.GetLastBookingNo", con);
        bookNo = Convert.ToInt32(cmd.ExecuteScalar());
        MailMessage mm = new MailMessage("bookings@site.local", "me@gmail.com");
        mm.Subject = "Booking Ref:" + bookNo;
        mm.Body = "Name: " + name + "<br /><br />Email: " + email + "<br /><br />Guests: " + guests.ToString() + "<br /><br />Date: " + date.ToString() + "<br /><br />Time: " + time + "<br /><br />Notes: " + notes;
        mm.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.UseDefaultCredentials = true;
        smtp.Send(mm);

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

将按钮类型切换为“按钮”。 type="submit"将导致默认的帖子行为。

替代方法:向按钮添加单击处理程序,并在单击处理程序的末尾添加return false。这将阻止正常的帖子行为。

示例:

function submit() {
    // Stop the browser from submitting the form.
    event.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();
    var querystring = "";
    querystring += "&name=" + $('input[name=name]').attr('data-id');
    querystring += "&email=" + $('input[name=email]').attr('data-id');
    querystring += "&phone=" + $('input[name=phone]').attr('data-id');
    querystring += "&guests=" + $('input[name=guests]').attr('data-id');
    querystring += "&date=" + $('input[name=date]').attr('data-id');
    querystring += "&time=" + $('input[name=time]').attr('data-id');
    querystring += "&notes=" + $('input[name=notes]').attr('data-id');
    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('Bookings.ashx?method=ProcessRequest&'+querystring),
        data: formData
    }).done(function (response) {

        // Clear the form.
        $('#input_name').val('');
        $('#input_email').val('');
        $('#input_phone').val('');
        $('#input_guests').val('');
        $('#datepicker').val('');
        $('#time').val('');
        $('#input_notes').val('');
    }).fail(function (data) {

        return false;
    });

    return false;
}

按钮:

<button type="submit" onclick="submit();">Book now</button>