我是 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 选择器 & '.'上课所以$('.contents').html(response);
如果你想为 DOM 使用类,将是代码。
在 php 部分 functions.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>
关于javascript - PHP 脚本不等待 Ajax 和 jQuery document.ready,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59455251/