Joh*_*ny5 5 javascript asp.net ajax asp.net-mvc jquery
假设我有一个表格:
<form id="myForm" method="POST" action="/something/somewhere">
<input type="text" name="textField" />
<input type="submit" name="foo" value="bar" />
</form>
Run Code Online (Sandbox Code Playgroud)
该/something/somewhere操作不会返回完整的html页面,只会返回一个片段.
我想让提交按钮执行其发布工作,但抓住这篇文章的结果并将其注入DOM中的某个位置.
jQuery submit发生在实际提交表单之前.它如何工作的例子是:
$('#myForm').posted(function(result)
{
$('#someDiv').html(result);
});
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
您可以使用jQuery .post()和.serialize()方法.
.post()使用HTTP POST请求从服务器加载数据.
.serialize()将一组表单元素编码为字符串以进行提交.
.preventDefault()如果调用此方法,则不会触发事件的默认操作.在你的情况下正常提交.
HTML
<form id="myForm" method="POST" action="/My/MyActionMethod">
<input type="text" name="textField" />
<input type="submit"/>
</form>
<div id="someDiv"></div>
Run Code Online (Sandbox Code Playgroud)
jQuery的
$(function() {
$('#myForm').live('submit', function (e) {
var form = $(this);
e.preventDefault();
$.post(form.attr('action'), form.serialize(), function (result) {
$('#someDiv').html(result);
});
});
});
Run Code Online (Sandbox Code Playgroud)
MVC控制器
public class MyController : Controller
{
[HttpPost]
public ActionResult MyActionMethod(FormCollection forms)
{
// do something with forms["textField"];
return Content("<b>Hello World!</b>");
}
}
Run Code Online (Sandbox Code Playgroud)
如果你无法让它工作(感谢IE),试试吧
event.preventDefault ? event.preventDefault() : event.returnValue = false;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
799 次 |
| 最近记录: |