2013-10-17 149 views
0

我希望在我的jquery-mobile网页上有一个“联系我们”表单。当用户输入所有数据并按下提交时,应该向asp脚本发出ajax post请求。如果asp脚本成功,它将通过json向发出请求的javascript代码回复成功状态。然后,我将切换到另一个页面,在同一个html文档中显示“您的邮件已发送”。提交表单以触发ajax请求

我见过一个例子,它不使用<form><input>标签。

是否有可能通过<form>做我想要的东西?

你会如何做到这一点在HTML方面和你会使用什么JavaScript事件?

+1

http://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax –

+1

jQuery的['。 submit()'](http://api.jquery.com/submit/)和['$ .ajax()'](http://api.jquery.com/jQuery。ajax /)函数应该让你开始。 –

+0

@你链接到的例子不是我期待的,因为它转换到另一个网址。我想保持在同一个网址,因为jquery-mobile文档可以有多个页面:jquerymobile.com/demos/1.2.1/docs/pages/multipage-template.html – Baz

回答

1

试试这个例子:
HTML

<form name="contactForm" id="contactForm"> 
    <input type="text" name="firstname" value=""> 
    <input type="submit" name="submit" id="submitBtn" value="Submit"> 
</form> 

JS

$(document).ready(function() { 
    $("#submitBtn").click(function() { 
     var formData = $("#contactForm").serialize(); 
     $.ajax({ 
      type: "POST", 
      url: "YOUR FILE PATH", //serverside 
      data: formData, 
      beforeSend: function() { 
       //show loading image 
      }, 
      success: function (result) { 
       console.log(result); //use this to see the response from serverside 
      }, 
      error: function (e) { 
       console.log(e); //use this to see an error in ajax request 
      } 
     }); 
    }); 
}); 
0

因为我从你的问题行了解 - “我会再切换到另一个网页非常相同的HTML文档中,并显示‘你的消息已发送’。 “ - 除了卫生署...的答案,如果你想要去到另一页上的成功ajax调用之前您序列化表单数据后添加此

var goto=$('#yourFormId').attr('href') 

,并在随后成功回调使用goto。 。

success: function() 
{ 
    //at the end include this: 
    location.href=goto; 

} 

注:你可以将任何地址分配给goto,在成功的时候打开地址

为JQM多页面结构,你可以触发AJAX的单击事件成功。假设你在你的html页面中有这个。

<div data-role="page" id="page-one" data-title="Page 1"> 
    <div data-role="header"> 
     <h1>Page 1</h1> 
    </div> 
    <div data-role="content"> 
     <p>Body copy for page 1</p> 
     <p><a href="#page-two" id="toPage2">Link to page 2</a></p> 
    </div> 
    <div data-role="footer"> 
     Copyright 
    </div> 
</div> 
<div data-role="page" id="page-two" data-title="Page 2"> 
    <div data-role="header"> 
     <h1>Page 2</h1> 
    </div> 
    <div data-role="content"> 
     <p>Body copy for page 2</p> 
     <a href="#page-one" id="toPage1">Link to page 1</a> 
    </div> 
    <div data-role="footer"> 
     Copyright 
    </div> 
</div> 

而且成功要打开Page 2 id为page-two。现在的Page 2链接是在div Page 1<a>标签。所以最后,而不是在阿贾克斯成功回调使用location.href你可以使用jQuery .trigger()

success: function() 
{ 
    $('a#toPage2').trigger('click',function(){}) 

} 
+0

您可以在jquery-mobile文档中拥有多个页面:http://jquerymobile.com/demos/1.2.1/docs/pages/multipage-template.html – Baz

+0

@巴兹我想念你的问题是关于jQuery的手机。这是我第一次使用jQuery手机,并阅读了一些例子和文档后,我编辑了我的答案。希望这会有所帮助。但是,我发现这个YouTube教程非常有用,请看看,如果你有兴趣http://www.youtube.com/watch?v=3AlvL7HuwqE – UDB