使用 AJAX 加载屏幕时无法接收 php 回显
Cannot receive php echo when using AJAX for loading screen
所以我试图在执行 php 文件时为网页做一个加载屏幕,因为 php 文件从 MYSQL 服务器获取数据,这可能需要有时一段时间。
所以我的 php-文件被命名为 "connect.php" 并回显 html 代码并且在调用时不需要任何参数。这是一个简单的概述,因此您可以了解它的作用。当我不使用 AJAX 并正常包含它时,整个文件都有效。
<?php
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
//MYSQL-Connection
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo //// Some HTML Code
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
还有我的 index.php,我使用 AJAX 调用 php 文件:
<section id="intro" class="wrapper style1">
<style>#loading { display:none; }</style>
<div id="loading">Test</div>
<div class="container">
<span>
<script>
$( '#loading' ).show();
$.ajax( {
url: 'connect.php',
type: 'POST',
dataType: 'html',
success: function () {
$( '.container' ).html();
$( '#loading' ).hide();
},
error: function () {
alert( "Something went wrong!" );
}
} );
</script>
</span>
</div>
</section>
所以控制台在很短的时间内没有出现任何错误(当 php 加载时 "Test" 字样打印在屏幕上,但随后什么也没有发生,我不知道为什么。而且就像我说的那样,当我像这样包含 php-文件时 <?php include_once('getcelebration.php'); ?>
一切正常。
您在 success
函数中缺少 data
参数,因为这些是回调函数,它们 return 从 request_url
传递的数据是 connect.php
在您的 AJAX 请求中。
试试这个:
success: function (data) {
console.log(data);
$( '.container' ).html(data);
$( '#loading' ).hide();
}
所以我试图在执行 php 文件时为网页做一个加载屏幕,因为 php 文件从 MYSQL 服务器获取数据,这可能需要有时一段时间。
所以我的 php-文件被命名为 "connect.php" 并回显 html 代码并且在调用时不需要任何参数。这是一个简单的概述,因此您可以了解它的作用。当我不使用 AJAX 并正常包含它时,整个文件都有效。
<?php
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
//MYSQL-Connection
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo //// Some HTML Code
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
还有我的 index.php,我使用 AJAX 调用 php 文件:
<section id="intro" class="wrapper style1">
<style>#loading { display:none; }</style>
<div id="loading">Test</div>
<div class="container">
<span>
<script>
$( '#loading' ).show();
$.ajax( {
url: 'connect.php',
type: 'POST',
dataType: 'html',
success: function () {
$( '.container' ).html();
$( '#loading' ).hide();
},
error: function () {
alert( "Something went wrong!" );
}
} );
</script>
</span>
</div>
</section>
所以控制台在很短的时间内没有出现任何错误(当 php 加载时 "Test" 字样打印在屏幕上,但随后什么也没有发生,我不知道为什么。而且就像我说的那样,当我像这样包含 php-文件时 <?php include_once('getcelebration.php'); ?>
一切正常。
您在 success
函数中缺少 data
参数,因为这些是回调函数,它们 return 从 request_url
传递的数据是 connect.php
在您的 AJAX 请求中。
试试这个:
success: function (data) {
console.log(data);
$( '.container' ).html(data);
$( '#loading' ).hide();
}