【问题标题】:Loading content on tab click在选项卡单击时加载内容
【发布时间】:2015-02-07 19:28:20
【问题描述】:

我最近发现了一个很酷的选项卡式内容页面,当您单击选项卡时,它们会显示内容http://codepen.io/unasAquila/pen/nDjgI 我发现这些选项卡是在您进入页面后预加载的,而不是在单击选项卡时加载上。我想知道是否可以在单击选项卡时将其加载到内容加载位置。例如,如果我有一个 PHP 查询语句,我想在其中加载如下信息:

 $query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");

 while($row = mysqli_fetch_array($query3))
 {
    echo "$row[name]
 }

只有在单击选项卡后才加载内容的位置?

【问题讨论】:

  • 关于代码问题的问题应该有相关代码在问题本身。了解如何创建MCVE,然后编辑您的问题以改进它。

标签: php mysql ajax


【解决方案1】:

可以使用AJAX 完成。简单来说,AJAX 是一种允许在前端触发事件时向后端发送请求的技术。

您可以进行以下操作:

在您的 HTML 中:

<!-- Change myTabId to whatever id you want to send to the server side -->
<element onclick="loadTab(myTabId)">my tab</element>

在你的 JS 中:

// Will be executed on tab click
function loadTab(tabId) {
    var xmlhttp = new XMLHttpRequest();
    // Define a handler for what to do when a reply arrives from the server
    // This function will not be executed on tab click
    xmlhttp.onreadystatechange = function() {
        // What to do with server response goes inside this if block
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // Change the content of the element with id "myTabContent" to the server reply
            document.getElementById("myTabContent").innerHTML = xmlhttp.responseText;
        }
    }
    // Opens a connection to "myServerSideScript.php" on the server
    xmlhttp.open("GET", "myServerSideScript.php?id=" + tabId, true);
    xmlhttp.send();
}

现在您需要在服务器根目录上创建myServerSideScript.php,其内容类似于以下内容:

$id = $GET[id];    //The GET parameter we sent with AJAX
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
$response = "";
while ($row = mysqli_fetch_array($query3)){
    $response .= $row[name];
}
// To return a reply you just need to print it
// And it will be assigned to xmlhttp.responseText on the client side
echo $response;

您可以了解更多关于 AJAX here

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多