我在 jquery 中使用 ajax post 来构建页面的一部分。但问题是它只运行一次。下面是我的代码
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
var dat = '';
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id },
success: function(data){
res = data;
data += '<div class="white" id="white" style="display:none">';
var result = $.parseJSON(res);
$.each(result, function(k, v) {
//display the key and value pair
dat += "<a href = 'javascript:void(0);' onclick='on("+ k +")'>"+ v+"</a><br>";
});
document.write(dat);
}
});
}
</script>
</head>
<body>
<a href="javascript:void(0);" onclick="on(8);">Get JSON data</a>
</body>
</html>
第一次点击后,页面在显示结果后继续加载。第二次单击后,它显示错误 ReferenceError: on is not Defined
。
实际上,每次点击 href id 都会传递到 jquery 函数中,并基于运行返回数据并显示新页面数据的 SQL 查询。每次点击 href 时都会发生这种情况。
最佳答案
您确实应该重新考虑您的事件处理:
$(function() {
var res;
$(".getJson").click(function (e) {
e.preventDefault();
var dat = '';
var id = $(this).data(id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id},
success: function(data) {
res = data;
data += '<div class="white" id="white" style="display:none">';
var result = $.parseJSON(res);
$.each(result, function(k, v) {
//display the key and value pair
dat += "<a href = 'javascript:void(0);' onclick='on(" + k + ")'>" + v + "</a><br>";
});
$("#output").append(dat);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<a href="javascript:void(0);" data-id="8" class="getJson">Get JSON data</a>
<span id="output"></span>
关于javascript - Jquery ajax 仅在第一次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41355223/