我有一个表单,可以将数据传递到同一页面上的 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 脚本中检索收藏夹的值,该脚本动态生成 MySQL 查询。但这是因为页面被重新加载而发生的。如果可能的话,我想使用 AJAX 将表单数据/变量传递给 jQuery 脚本,而无需重新加载页面。我知道我可以使用 AJAX 操作 html 和 css,但是我也可以操作 head 中的 jQuery 脚本吗?如果是这样,我该怎么办?
最佳答案
为了简单起见,为表单指定一个唯一的 ID,然后只需将 jquery post 发送到为此目的设计的 AJAX 文件即可。
示例:
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.
});
});
这至少是我开始的地方:)
关于php - 我可以使用 AJAX 将表单数据/变量传递到 jQuery 脚本中的 php 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917345/