PHP 脚本不等待 Ajax 和 jQuery document.ready



我是PHP和Ajax的新手。我正在开发一个供个人使用的动态网站,这要求网站响应客户的窗口宽度。

目前,它被设置为通过Ajax GET请求发送宽度,只需将大小打印回屏幕,尽管此PHP脚本将在页面加载之前打印响应,在页面顶部留下静态的"宽度<1275",永远不会被删除。

我将如何解决这个问题?谢谢

.HTML

<body>
<div class="contents">
</div>
</body>

JavaScript

$(document).ready(function() {
var width = $(window).width();
$.ajax({
url: 'functions.php', 
type: 'GET', 
data: {size : width},
success: function(response) {
$('#contents').html(response);
}
});
$(window).resize(function() {
var width = $(window).width();
$.ajax({
url: 'functions.php', 
type: 'GET', 
data: {size : width},
success: function(response) {
$('#contents').html(response);
}
});
});
});

.PHP

<?php
$width = $_GET['size'] ?? '';
if($width < 1275)
{
echo('<div class="column">' . 'width < 1275' . '</div>');
}
else
{
echo('<div class="column">' . 'width > 1275' . '</div>');
}
?>

好吧,你的js代码很好。 1s 确保你有 jquery, 这是CDN:https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js, 然后将<div class="contents">更改为<div id="contents">因为$('#contents').html(response);"#"代表ID选择器,"."代表类,所以如果你想将类用于DOM,$('.contents').html(response);将是代码。 在 PHP 部分函数中.php做这样的事情:

<?php
if(isset($_GET['size'] )){
$width = $_GET['size'] ;
if($width < 1275)
{
echo('<div class="column">' . 'width < 1275' . '</div>');
}
else
{
echo('<div class="column">' . 'width > 1275' . '</div>');
}

}
else{
echo " nothing found";
}
?>

这是我的索引页:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<body>
<div id="contents">
</div>
</body>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
var width = $(window).width();
resize(width);

$(window).resize(function() {
var width = $(window).width();
resize(width);
});

function resize(width){
$.ajax({
url: 'functions.php', 
type: 'GET',
data: {size : width},
success: function(response) {
console.log(response);
$('#contents').html(response);
}
});
}
});


</script>

使用以下async: false尝试您的 AJAX 代码:

$(document).ready(function() {
var width = $(window).width();
$.ajax({
url: 'functions.php', 
type: 'GET', 
async: false,
data: {size : width},
success: function(response) {
$('#contents').html(response);
}
});
$(window).resize(function() {
var width = $(window).width();
$.ajax({
url: 'functions.php', 
type: 'GET', 
async: false,
data: {size : width},
success: function(response) {
$('#contents').html(response);
}
});
});
});

最新更新