簡體   English   中英

AJAX 加載內容到頁面

[英]AJAX loading content into page

我正在嘗試使用 AJAX 在我的服務器上包含一個文件,唯一的問題是它會阻止我的 php 代碼工作。

我正在使用 ajax 的頁面位於:

<div id="content">
<!--- HERE GOES CONTENT --->
</div>
<script>
$.ajax({
    url: 'https://mywebsite.com/func/contentpage.php',
    dataType: 'html'
})
.done(function(data) {
    // Assuming the request returns HTML, replace content
    $('#midten').html(data);
});
    </script>

contentpage.php 代碼:

<?php
$g1 = $database->query("SELECT * FROM `users` WHERE `sesid` = '" . $_SESSION["uises"] ."' AND abd='" . $_SESSION["uiabd"] ."'");
$ui2 = $g1->fetch_object();

echo $ui2->name;
?>

上面的代碼應該從數據庫中回顯一個名字,但由於某種原因它沒有。

如果我使用 php 並包含這樣的頁面: include("/func/contentpage.php")它會毫無問題地回顯名稱。

但是當嘗試使用 ajax 加載頁面時,它不會回顯名稱或任何內容。 我使用 AJAX 的原因是在單擊按鈕時加載內容而無需重新加載瀏覽器。

如何使用 AJAX 或其他方法解決此問題? 我可以在 php 中使用來更改 include 中的路徑,而無需重新加載網頁/再次加載整個網站。

出於調試目的,您可以回顯除名稱以外的任何其他內容,但是如果您的 PHP 文件中存在錯誤,那么開發人員控制台中將會出現一條消息,例如502 internal server error

您的contentpage.php缺少很多聲明和引用。

<?PHP
session_start();//since you are using sessions here
$database = something;//undefined variable
//better use a file where you have declared all the variables and 
//then include it here
require variables.php;//something like this
$g1 = $database->query("SELECT * FROM `users` WHERE `sesid` = '" . $_SESSION["uises"] ."' AND abd='" . $_SESSION["uiabd"] ."'");
$ui2 = $g1->fetch_object();

echo $ui2->name;
?>

有關實際問題的更多信息,請訪問https://mywebsite.com/func/contentpage.php使用 URL,如果您啟用了error_reporting() ,您將看到錯誤。

如果.php中沒有錯誤,那么您需要檢查您的 ajax。

將數據類型 HTML 替換為文本,因為文本中的返回響應不是 html,因為該響應為空

嘗試這個:

<div id="content">
<!--- HERE GOES CONTENT --->
</div>
<script>
$.ajax({
    url: 'https://mywebsite.com/func/contentpage.php',
    dataType: 'text'
})
.done(function(data) {
    // Assuming the request returns HTML, replace content
    $('#midten').html(data);
});
    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM