[英]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.