我有一个表单,它将数据传递到同一页上的jQuery脚本。表单如下所示:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="radio" name="favourites" value="all" checked="checked"> all tracks   <input type="radio" name ="favourites" value="favourites"> favourites only<br><br>
<input type="submit" name="submit" id="filter" class="submit" value="filter"><br>
</form>
然后,PHP在同一页面头部的jQuery脚本中检索favourites的值,该脚本动态地生成一个MySQL查询。但是发生这种情况是因为页面被重新加载。如果可能,我希望使用AJAX在不重新加载页面的情况下将表单数据/变量传递给jQuery脚本。我知道我可以使用AJAX操作html和css,但我也可以操作头部的jQuery脚本吗?如果是这样,我该怎么做呢?
发布于 2012-08-11 20:35:17
为了简单起见,给表单一个惟一的ID,然后简单地向一个专门为此目的设计的AJAX文件创建一个jquery post。
示例:
HTML
<form id="postForm" method="POST">
<input type="radio" name="filter" value="1" /> Only favorites
<input type="radio" name="filter" value="2" /> Everything
<input type="submit" name="postFormSubmit" />
</form>
jQuery
$('form#postForm').submit(function(e){
e.preventDefault(); //Prevents a page reload
var filter = $(this).find("input[@name=filter]:checked").val(); //Gets the value of "filter"
$.post("/path/to/ajax.php",{filterType:filter},function(){
// Callback, could make the data output attach to this.
});
});
这至少是我开始的地方:)
发布于 2012-08-11 20:51:57
看看this吧。代码应该是这样的。
HTML:
<form id="postForm" method="POST">
<input type="radio" name="filter" value="1" /> Only favorites
<input type="radio" name="filter" value="2" /> Everything
<input type="submit" name="postFormSubmit" />
</form>
Javascript:
jQuery("#postForm").submit(function(event){
event.preventDefault();
jQuery.post("/ajax.php", jQuery("#postForm").serialize(), function(){
//done
});
}
发布于 2012-08-11 22:26:38
如果您不想自己编写它,您可能会对这个插件http://jquery.malsup.com/form/感兴趣
https://stackoverflow.com/questions/11917345
复制