簡體   English   中英

JavaScript - 單擊按鈕加載新的 html 頁面

[英]JavaScript - Load new html page with button click

我正在使用 Nodejs 運行 http 服務器。 最初,有一個帶有文本條目的登錄頁面,您可以在其中輸入昵稱和一個按鈕,該按鈕將帶您進入新的 html 頁面。

該按鈕將玩家及其昵稱添加到玩家列表中。 但是,它不會加載新的 html 頁面。

這是服務器代碼:

const http = require('http');
const fs = require('fs');

console.log('running');

let player_count = 0;
let players = [];

class player
{
    constructor(id)
    {
        this.id = id;
        this.name = "";
        this.card_czar = false;
        this.cards = new Set();
        this.score = 0;
        this.selection = "";
    }

    setName(nick_name)
    {
        this.name = nick_name;
    }

    setCardCzar(czar_boolean)
    {
        this.card_czar = czar_boolean;
    }

    delCard(card_val)
    {
        this.cards.delete(card_val);
    }

    addCard(card_val)
    {
        this.cards.add(card_val);
    }

    addScore()
    {
        this.score++;
    }
}

let server = http.createServer(async (req, res) => {
    console.log(req.url);

    if (req.url == '/') {
        res.write(fs.readFileSync('../frontend/test.html'));
    }
    else if (req.url == '/login') {
        const buffers = [];

        for await (const chunk of req) {
            buffers.push(chunk);
        }

        let buffer = Buffer.concat(buffers).toString()
        const data = await JSON.parse(buffer);

        new_player = new player(player_count);
        new_player.setName(data.nickname);
        players.push(new_player);

        player_count++;

        res.write(fs.readFileSync('../frontend/cardcast.html'));

        console.log(players)
    }

    res.end();
});

server.listen(3000);

這是客戶端代碼:

<html>  
    <head>  
    <script type = "text/javascript">  
        async function login()
        {
            let nickname = document.getElementById('username-field').value;
            console.log(nickname);

            let url = window.location.href + 'login';
            
            let res = await fetch(url, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({nickname})
            });
        }
    </script>  
    </head>
    <style>
        .login-form-field {
        border: none;
        border-bottom: 1px solid #3a3a3a;
        border-top: 1px solid #3a3a3a;
        margin-bottom: 10px;
        border-radius: 3px;
        outline: none;
        padding: 0px 0px 5px 5px;
        }

        #login-form-submit {
        width: 100%;
        padding: 7px;
        border: none;
        border-radius: 5px;
        color: white;
        font-weight: bold;
        background-color: #3a3a3a;
        cursor: pointer;
        outline: none;
        }
    </style>
    <body>  
        <p>Welcome To Cards Against Mill House</p>
        <div id="New Accident" class="tabcontent">
            <input type="text" name="username" id="username-field" class="login-form-field" placeholder="Nickname">
  
            <button onclick = "login()" value = "Login">Login</button> 
        </div>
    </body>  
</html>  

服務器文件位於后端文件夾中,文件 cardcast.html 位於前端文件夾中。 我希望它在玩家輸入他們的昵稱后加載 cardcast.html 文件,這樣他們就可以開始玩游戲了。

任何幫助實現這一點將不勝感激! 提前致謝!

我相信客戶端代碼上的res應該存儲 HTML 響應。 您是否嘗試過打印它以查看它的內容?

您可能想閱讀這篇文章,其中介紹了如何從 fetch 響應中注入 HTML。

/login的服務器處理程序應該返回一個值,它確實如此。 它是文件cardcast.html的內容。 如果您查看“網絡”選項卡,您會發現正在發生的事情。 該內容可能應該是 JSON,但是您對客戶端的響應什么也不做。

你期待會發生什么? 如果您想加載頁面,那么您根本不需要使用 Ajax。 您需要重定向 使用<form>標簽會簡化這個過程。

 // server, handle POST if (req.url == '/login') { var nickname = req.body.username new_player = new player(player_count); new_player.setName(nickname); players.push(new_player); player_count++; res.write(fs.readFileSync('../frontend/cardcast.html')); console.log(players) }
 <div id="New Accident" class="tabcontent"> <form action="/login" method="post"> <input type="text" name="username" id="username-field" class="login-form-field" placeholder="Nickname"> <button value="Login">Login</button> </form> </div>

我最終通過將響應讀取為文本並將 document.body.innerHTML 設置為它來解決問題。

async function login()
        {
            let nickname = document.getElementById('username-field').value;
            console.log(nickname);

            let url = window.location.href + 'login';
            
            let res = await fetch(url, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({nickname})
            });

            let data = await res.text();

            document.body.innerHTML = data;
        }

謝謝您的幫助!

暫無
暫無

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

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