我试图创建一个从按钮获取元素值并创建ajax请求的函数。在开始的#id;'是空的,所以下面的JS函数应该使用' id = 1'但当我点击按钮时,例如价值" 2"函数应加载"包括/ agallery.php?id = 2"到我的#agallery。
<script type="text/javascript">
var id = 1;
$('#agallery').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
$.ajax({
url: "includes/agallery.php?id="+id
}).done(function(data) { // data what is sent back by the php page
$('#agallery').html(data); // display data
});
</script>
<button onClick="" value="2" class="small-btn last"></button>
答案 0 :(得分:0)
您需要在每次请求之前增加id。
<script type="text/javascript">
var id = 0;
$('#agallery').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
id++;
$.ajax({
url: "includes/agallery.php?id="+id
}).done(function(data) { // data what is sent back by the php page
$('#agallery').html(data); // display data
});
</script>
答案 1 :(得分:0)
你可能需要这个
<script type="text/javascript">
$(".small-btn last").click(function () {
$('#agallery').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
$.ajax({
url: "includes/agallery.php?id="+$(this).val()
}).done(function(data) { // data what is sent back by the php page
$('#agallery').html(data); // display data
});
});
答案 2 :(得分:0)
doAjax
函数,该函数接受参数id
并生成ajax请求doAjax
1 id
来电
醇>
这就是你的代码中的样子:
<script type="text/javascript">
// create a function doAjax
function doAjax(id) {
$('#agallery').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
$.ajax({
url: "includes/agallery.php?id="+id
}).done(function(data) { // data what is sent back by the php page
$('#agallery').html(data); // display data
});
}
$(function() {
// register a click handler
$("button.small-btn").click(function() {
var id = $(this).val();
doAjax(id);
});
// do initial ajax request (with id 1)
doAjax(1);
});
</script>
在html中移除onClick=""
,以便元素如下所示:
<button value="2" class="small-btn last"></button>
这是一个有效的 jsFiddle demo