簡體   English   中英

根據網址動態加載內容

[英]Load content dynamically based on url

如何根據頁面的URL動態加載內容。

EG:profiles.html #example-contenet1,profiles.html#example-contenet2

對於每個#example-contenet加載不同的頁面內容。

我試圖把它放到一個JSFiddle,但我認為它可能需要一個PHP后端。 http://jsfiddle.net/JEUSz/3/

也許是這樣的:

switch ($_POST['name']) {
case 'example-name1':
    echo "<img src='img/pic.jpg' />"; 
    echo "<img src='img/pic.jpg' />";
    echo "hi";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
default:
    echo 'fail';
    break;
}

這是服務器端開發的全部目的。 閱讀有關路由的信息 ,並選擇這樣的PHP路由器

不,你不必使用PHP。 您只需創建多個HTML文件並將它們放入服務器即可。 然后,您可以使用AJAX加載特定內容(與哈希“#some-name”相關)。

嘗試這個:

http://tutorialzine.com/2009/09/simple-ajax-website-jquery/

使用PHP,您可以使用查詢字符串中的變量來確定正文的內容。 這是一個小網站的一個非常簡單的例子:

使用example.php?內容= CONTACT_FORM

<?php
$content = isset($_GET['content']) ? trim($_GET['content']) : 'default';

switch($content){
    case 'contact_form':
        include('html/contact_form.php');
        break;
    case 'welcome':
        include('html/welcome.php');
        break;
    default:
        include('html/default.php');
}

要么:

<?php
$contentPages = array(
    'contact_form' => 'contact_form.php',
    'welcome' => 'welcome.php',
    'about' => 'about.php'
);

$content = 'default.php';
if(isset($_GET['content']) && array_key_exists($_GET['content'], $contentPages)){
    $content = $contentPages[$_GET['content']];
}

include('html/' . $content);

您的示例代碼非常好,但您必須使用變量而不是哈希標記。

因此,不是profiles.html#example-contenet1,而是profiles.html?name = example-content1

然后你的switch語句將正常工作。

有關$ _GET變量的一些其他信息: http//www.w3schools.com/php/php_get.asp

服務器不會獲取URL的哈希標記部分,有關詳細信息,您可以查看此問題:

我可以在服務器端應用程序(PHP,Ruby,Python等)上讀取URL的哈希部分嗎?

為每個頁面使用js文件。

index.html => index.js
guestbook.html => guestbook.js

等等。 這很好,因為你需要在不同的頁面中使用不同的實現。 如果要在頁面上共享功能,請使用global.js並在每個頁面中包含此文件。

我就是這樣做的。 在php文件里面我更​​改了$ template。

//Get content
$template = file_get_contents("main.html");

//Content based on _GET['page'] value
switch($_GET['page']){
    case "home": //Form Page
        include("inc/form_year.php");
        break;
    case "company_register": //Form Page
        include("inc/company_register.php");
        break;
    case "confirm_user": 
        include("inc/confirm_user.php");
        break;
    case "posts": 
        include("inc/posts.php");
        break;
    case "question": 
        include("inc/question.php");
        break;
    case "post_question": 
        include("inc/post_question.php");
        break;
    case "post_answer": 
        include("inc/post_answer.php");
        break;
    case "comment": 
        include("inc/comment.php");
        break;
    case "create_post": 
        include("inc/create_post.php");
        break;
    default: //Any page that is not defined in this switch will lead to this page
        include("inc/form_year.php");
}

暫無
暫無

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

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