jQuery AJAX的if else语句未运行

时间:2018-09-21 21:11:57

标签: javascript jquery ajax

当我插入代码片段并在Stack Overflow上运行时,它会显示'$ is missing'!但是,唯一的问题是HTTP/1.1 301 Moved Permanently Server: nginx/1.4.6 (Ubuntu) Date: Mon, 04 May 2015 18:20:19 GMT Content-Type: text/html Content-Length: 193 Connection: keep-alive Location: http://www.example.com/ if语句无法检查预订号是否为全部号码。 AJAX函数运行,流程流向后端,并持久保存数据。我很困惑这段代码有什么问题吗?

else
clickme = function() {
  alert("hiiiiiii")
  var selected = $('input:checked');
  var chosen_emails = [];
  selected.each(function() {
    chosen_emails.push($(this).val());
  });

  var re = /[0-9]/;
  var booking_address = document.forms["contact"]["booking_address"].value;

  var booking_number = document.forms["contact"]["booking_number"].value;
  var booking_message = document.forms["contact"]["booking_message"].value;

  var booking_date = document.forms["contact"]["booking_date"].value;
  alert("booking address is" + booking_address + "booking_number is" + booking_number + "booking message is" + booking_message + "booking date is:" + booking_date);

  array = chosen_emails + "" //converting choosen_emails to string type 

  alert("choosen techies are:" + chosen_emails);

  var currentdate = new Date();
  var request_date = currentdate.getDate() + "/" +
    (currentdate.getMonth() + 1) + "/" +
    currentdate.getFullYear() + " @ " +
    currentdate.getHours() + ":" +
    currentdate.getMinutes() + ":" +
    currentdate.getSeconds();

  var user_email = "${user_email}";

  if (booking_number.length < 8) {
    alert("must not be less than 8 numbers");
  } else if (!re.test(booking_number)) {

    alert("Error: must not contain any characters!");
  } else {
    $(function() {
      $.ajax({ // defining the below function as ajax responsive//
        url: 'service_request', // the function that process the  mapped url name and matching type is going to receive the data//
        type: 'POST',
        data: {
          chosen_emails_1: chosen_emails[2],
          chosen_emails_2: chosen_emails[3],
          chosen_emails_3: chosen_emails[4],
          booking_address: booking_address,
          booking_number: booking_number,
          booking_message: booking_message,
          booking_date: booking_date,
          request_date: request_date,
          user_email: user_email
        }, // function to get the value from jsp page and send it to mapped class function//
        success: function(response) { // if the backend process is success then the function will run by getting the response as its parameter//
          alert(response.message);
        },
        error: function(response) {
          alert("there was an error processing your request");
        }
      });
    });
  }
}

//to set limit for number of checkboxes to be selected

$(document).ready(function() { //Its crucial that we are Wrap the code in ready() callback, so that the code (on change event handler) will be executed after DOM is finished loading (response data)
  $("#table").on("click", function() {
    var limit = 3,
      checkboxes = $(this).find("input:checkbox"),
      valid = checkboxes.filter(":checked").length >= limit;
    if (valid) {
      checkboxes.not(":checked").attr("disabled", valid);
      $('.container').show();
    }
  });
});

1 个答案:

答案 0 :(得分:2)

您的正则表达式匹配包含至少一个数字的字符串:

var re = /[0-9]/;
re.test('39583902'); // true
re.test('mostly letters but also 1 number'); // true
re.test('entirely letters'); // false

反转正则表达式和if条件的逻辑:

var re = /[^0-9]/;
...
else if (re.test(booking_number)) {
  alert('Numbers only, please');
}

您还可以从点击处理程序中删除所有验证代码,然后让浏览器进行处理:

$(document).ready(function() {
  $("#contact").on("submit", function(evt) {
    console.log("in the form's submit handler");
    evt.preventDefault();
    // Run your AJAX here
  });
});
label {
  display: block;
  margin: 0.5em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Enter your details to successfully complete the service request </p>
<form id="contact" action="" method="post">
    <label>
      Your Address
      <input placeholder="123 Anywhere St." type="text" tabindex="1" name="booking_address" required>
    </label>
    <label>
      Your number
      <input type="text" tabindex="2" placeholder="12345678" name="booking_number" id="booking_number" required pattern="^\d+$" minlength="8" title="Must contain only numbers" required>
    </label>
    <label>
      Select your date and time
      <input type="datetime-local" id='datetime' placeholder="2015-10-21T16:29" name="booking_date" tabindex="3" required>
    </label>
    <label>
      Message (optional)
      <textarea placeholder="Placeholders are for example data, not a prompt." tabindex="4" name="booking_message"></textarea>
    </label>
    <button name="submit" type="submit" id="contact-submit">Submit</button>
</form>

我在预订号minlength上添加了<input>属性,并修复了其验证正则表达式(HTML只需要该正则表达式的内容,其转义字符为&;无需逃脱\d)。

浏览器不会提交未经验证的表单,因此您可以将AJAX放入表单的submit处理程序(而不是提交按钮的click处理程序)中,并且只能与有效数据。请确保在活动中致电preventDefault(),以便提交表单不会重新加载页面。