第一次AJAX尝试.....我正在尝试更新一个基于一个选择与一个按钮。
我目前只是提醒ID返回,因为这是我能弄清楚该做什么。
是否可以将文件my_page.php放入div类"populated_info"?然后,当我按下另一个按钮时,页面函数将再次运行,并用新的结果填充div。我有my_page.php已经建立和运行基于ID,只是不能让它渲染在正确的地方。
HTML: <form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX: <script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
方法:
关于你的按钮,我建议分离内联Javascript处理程序,以保持你的HTML和Javascript分开。我将在这里使用自定义数据属性来存储ID:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
然后jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
AJAX请求:
您可以缩短整个函数并使用$.load()
将数据放入div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
在这里看起来不需要回调函数,但是如果需要的话,可以把它放在data参数后面。这里回调的一个有用的应用可能是用于错误处理程序。请看这里如何实现一个。
顺便说一句,如果你只是获取数据,你可能应该使用GET HTTP方法而不是POST。
如果您成功地从服务器获得replace alert(resp)
与$('.populated_info').html(resp);
的响应
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>