我正在构建一个列出许多文件的应用程序。页面底部有一个按钮,显示“查看较旧”,我想用它来加载旧文件列表。目前,单击按钮时工作正常;它重新加载页面,并且在设置提交时显示较旧的页面。但是,如果没有重新加载,我宁愿这样做。
我如何使用AJAX执行此操作?这是我到目前为止所做的:
<div class="row">
<div class="col-xs-12">
<form method="GET">
<input type="submit" name="submit" value="View Older" id="submit" />
</form>
</div>
<div class="col-xs-12 listholder">
<ul class="list-group">
<?php
if( isset($_GET['submit']) ){
$old_directory = 'oldeshots';
$scanned_old = array_diff(scandir($old_directory), array('..', '.'));
foreach ($scanned_old as $key => $value) {
echo '<li class="list-group-item">';
echo "<a href='$value?old=true'>$value</a>";
echo '</li>';
}
} ?>
</ul>
</div>
</div>
到目前为止的AJAX代码(目前还没有太多内容!):
$('#submit').on('click', function(e){
e.preventDefault();
$.ajax( {
url:'index.php',
data: , //What goes here?
success:function(data) {
//What goes here?
}
});
});
我玩过jQuery .ajax(),但是我没看到它如何设置$ _GET变量。也许我接近这个错误的方式?任何帮助将不胜感激。
由于
答案 0 :(得分:2)
<强> getfiles.php 强>:
<?php
$old_directory = 'oldeshots';
$scanned_old = array_diff(scandir($old_directory), array('..', '.'));
echo json_encode($scanned_old);
ajax代码:
$('#submit').on('click', function(e){
e.preventDefault();
$.ajax({
url:'getfiles.php',
data: {myvar1: 'value', myvar2: 'value2'}, // You don't need this in this case. But this is how you use it.
dataType: 'json',
success:function(data) {
$.each(data, function(i,value){
$(".list-group").append('<li class="list-group-item"><a href="'+ value +'?old=true">'+value+'</a></li>');
});
}
});
});
答案 1 :(得分:1)
要使用Ajax + jQuery检索数据,您必须编写以下代码:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
答案 2 :(得分:0)
您的php文件
<div class="row">
<div class="col-xs-12">
<form method="GET">
<input type="submit" name="submit" value="View Older" id="submit" />
</form>
</div>
<div class="col-xs-12 listholder">
<ul class="list-group">
</ul>
</div>
</div>
ajax电话
$('#submit')。on('click',function(e){
e.preventDefault();
var data = 'oldeshots';
$.ajax( {
type : 'GET',
url:'getdata.php',
data: data,
success:function(data) {
$('ul.list-group').html(data);
}
});
});
<强>访问getdata.php 强>
<?php
if( isset($_GET['submit']) ){
$old_directory = $_GET['data'];
$scanned_old = array_diff(scandir($old_directory), array('..', '.'));
foreach ($scanned_old as $key => $value) {
echo '<li class="list-group-item">';
echo "<a href='$value?old=true'>$value</a>";
echo '</li>';
}
}
?>