![](/img/trans.png)
[英]jQuery document.ready doesn't fire after script called in code behind ScriptManager.RegisterStartupScript
[英]PHP script doesn't wait for Ajax and jQuery document.ready
我是 PHP 和 Ajax 的新手。 我正在开发一个供个人使用的动态网站,它需要网站响应客户端的窗口宽度。
目前,这被设置为通过 Ajax GET 请求发送宽度并将大小打印回屏幕,尽管此 PHP 脚本将在页面加载之前打印响应,在永远不会被删除的页面顶部。
我将如何解决这个问题? 谢谢
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>
尝试使用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);
}
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.