如何使用<a href=""> link?</a>提交AJAX表单

时间:2013-11-06 01:06:29

标签: javascript jquery html ajax forms

我有以下表格:

<form id='confirm_reset' action='login/forgotPassword_action' method='post'>
<input type='hidden' name='user_email' value='user_email'>
<a href='#' onclick="confirm_reset.submit();">Submit</a>
</form>

<div id="alert_box_register"></div>

我试图用Ajax提交它以在警告框中返回JSON:

$("#confirm_reset").on("submit", function(event) {

   //disable default click operation
   event.preventDefault();

   var action_url = $(this).attr("action");

   alert_box_register("Resetting password...");

   console.log(action_url);

   var postData = $(this).serializeArray();
   console.log(postData);

   $.post(action_url, postData, function(data) { 
      console.log(data);
      var obj = $.parseJSON(data); 

      alert_box_register(obj.message); 
   });

});

此脚本不返回任何结果(就好像链接不起作用)。我哪里错了?

1 个答案:

答案 0 :(得分:0)

不确定此代码是否仍然存在问题......?

关于您的进度消息("Resetting password...")的快速说明:此代码可能运行得如此之快,以至于此消息几乎不会在屏幕上为用户闪烁。我不知道你的东西是如何设置的,但你可能永远不会在屏幕上看到这个。

<!-- The following line was missing .php from the action -->
<!--form id='confirm_reset' action='login/forgotPassword_action' method='post'-->
<form id='confirm_reset' action='login/forgotPassword_action.php' method='post'>
   <input name="txtbox" type="text" value="hello world"/>
   <input type='hidden' name='user_email' value='user_email'>

   <!-- submit_confirm_reset() is a function I made in the javascript tages-->
   <a href='#' onclick="submit_confirm_reset();">Submit</a>
</form>

<div id="alert_box_register"></div> 

<script>

function submit_confirm_reset() {
   $("#confirm_reset").submit(); 
}

$("#confirm_reset").on("submit", function(event) 
{ 
   console.log('("#confirm_reset").on("submit", function(event)');

   //disable default click operation
   event.preventDefault();

   var action_url = $(this).attr("action"); 

   // you were using alert_box_register like it was a function
   // but it doesn't exist in the code you posted in your question
   // but a DOM element has this name so I assume you meant that
   $("#alert_box_register").html("Resetting password..."); 
   console.log(action_url);

   var postData = $(this).serializeArray();
   console.log(postData);

   $.post(action_url, postData, function(data) { 
      console.log(data);

      // if this response is already json, you don't need to parse it 
      var obj = $.parseJSON(data);  
      $("#alert_box_register").html(obj.message); 
   }); 
});
</script>