0

I have a form on a page that accepts an 'ID', user inputs ID eg; 1026

The form submits to the same page ajax grabs the ID checks it against another site. I need to be able to let the form post if the response is NOT a 404 error and $_GET is true.

Heres what I have

<script>
$(document).ready(function(){
 $('form#getid').submit(function(){
  var theid = $('input#id').val();
  var dataString = "id=" + theid;
    $.ajax({
          type: "POST",
          data: dataString,
  success: function(response, status, xhr){
    if(status=="success") {
      $("#err-404").html(response);
    }
    else { alert(status+ ' - '+ xhr.status); }
  }
}
         }); 

  });

return false;
});
</script>

My form

<form id="getid" action="">
    <input type="text" name="id" />
    <input type="submit" class="button" value="Go">
<div class="error" id="err-404"></div>

I think im on the right track, just not sure how to put it all together.

4

1 回答 1

0

首先,如果您不必为数据使用字符串,请不要。您可以像这样使用数组:

$.ajax({
      type: "POST",
      data: {'id': theid },

这更清洁,更易于维护。

至于你的问题,你的代码有点不清楚,但你可能应该做的是return false在 submit() 事件结束时防止表单提交,然后在 AJAX 事件中,如果它被清除提交,做一个$('#getid').submit(). 您可能必须设置某种标志(隐藏输入或数据属性)以进行检查,以避免 AJAX 触发的提交再次检查,从而导致无限循环。

此处注意:404 应该会导致error()AJAX 处理程序中的回调触发,因此 404 不会触发您设置的成功回调。

于 2013-07-12T00:24:34.247 回答