我有 2 个单选按钮,用于在 2 个位置之间进行选择,以便在选择时可以从外部文件加载不同的 PHP 页面。但该文件确实还需要自动刷新,以便每 3 分钟显示最新信息。
这些是我的单选按钮:
<div class="locationdrop">
<div class="dropbtn">Location</div>
<div class="locationlist">
<input type="radio" id="location1" name="location" value="Location 1" class="locationinput" checked="checked">
<label for="location1" class="locationlabel">Location 1</label>
<input type="radio" id="location2" name="location" value="Location 2" class="locationinput">
<label for="location2" class="locationlabel">Location 2</label>
</div>
</div>
</div>
这是我的脚本(使用自动更新 AJAX):
<script>
$(document).ready(function() {
function getData() {
if(document.getElementById('location1').checked) {
$.ajax({
type: 'POST',
url: 'location1data.php',
success: function(data){
$('#locationoutput').html(data);
}
});
}else if(document.getElementById('location2').checked) {
$.ajax({
type: 'POST',
url: 'location2data.php',
success: function(data){
$('#locationoutput').html(data);
}
});
getData();
setInterval(function () {
getData();
}, 120000); // it will refresh your data every 3 mins
};
};
});
</script>
这是我将 php 加载到 div 的原始(工作)代码:
<script>
$(document).ready(function(){
function getData(){
$.ajax({
type: 'POST',
url: 'locationData.php',
success: function(data){
$('#locationoutput').html(data);
}
});
}
getData();
setInterval(function () {
getData();
}, 120000); // it will refresh your data every 1 sec
});
</script>
我只需要它使用单选按钮在其中两个之间进行选择。
非常感谢您的帮助:)
最佳答案
试试这个:
$(document).ready(function() {
function getData() {
if(document.getElementById('location1').checked) {
$.ajax({
type: 'POST',
url: 'location1data.php',
success: function(data){
$('#locationoutput').html(data);
}
});
}else if(document.getElementById('location2').checked) {
$.ajax({
type: 'POST',
url: 'location2data.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
};
getData();
setInterval(function () {
getData();
}, 120000); // it will refresh your data every 3 mins
});
这样效率更高
$(document).ready(function() {
let location_one = document.getElementById('location1');
let location_two = document.getElementById('location2');
let getLocationOneData = function () {
$.ajax({
type: 'POST',
url: 'location1data.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
let getLocationTwoData = function () {
$.ajax({
type: 'POST',
url: 'location2data.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
let getData = function () {
if (location_one.checked) {
getLocationOneData();
} else if (location_two.checked) {
getLocationTwoData();
}
}
location_one.addEventListener('change', function () {
if (this.checked) {
getLocationOneData()
}
});
location_two.addEventListener('change', function () {
if (this.checked) {
getLocationTwoData();
}
});
setInterval(function () {
getData();
}, 120000); // it will refresh your data every 3 mins
});
关于javascript - 我有 2 个单选按钮,我想根据选择的按钮将不同的 ajax 页面加载到 div 元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68598695/