自学内容网 自学内容网

使用rust+javascript+html5写一个问题记录的页面

为了实现一个简单的问题记录系统,我们可以使用Rust作为后端,JavaScript和HTML5作为前端。以下是一个简单的实现:

  1. 首先,我们需要创建一个Rust后端,用于处理问题记录的增删改查操作。这里我们使用warp库来创建一个简单的HTTP服务器。

安装依赖:

cargo install warp

创建一个名为main.rs的文件,内容如下:

use warp::Filter;

#[tokio::main]
async fn main() {
    let questions = warp::path("questions")
        .and(warp::get())
        .map(|| {
            // 这里可以从数据库或其他存储中获取问题列表
            "[]" // 返回一个空的问题列表
        });

    warp::serve(questions)
        .run(([127, 0, 0, 1], 3030))
        .await;
}
  1. 接下来,我们需要创建一个HTML页面,用于显示问题列表和添加新问题。创建一个名为index.html的文件,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>问题记录系统</title>
</head>
<body>
    <h1>问题记录系统</h1>
    <ul id="question-list"></ul>
    <form id="add-question-form">
        <input type="text" id="question-input" placeholder="输入问题">
        <button type="submit">添加问题</button>
    </form>
    <script src="app.js"></script>
</body>
</html>
  1. 然后,我们需要编写JavaScript代码来处理前端逻辑,包括获取问题列表、添加新问题等。创建一个名为app.js的文件,内容如下:
document.getElementById('add-question-form').addEventListener('submit', async (event) => {
    event.preventDefault();
    const questionInput = document.getElementById('question-input');
    const question = questionInput.value;
    if (!question) return;

    // 发送请求到后端API,添加新问题
    const response = await fetch('http://localhost:3030/questions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ question })
    });

    if (response.ok) {
        // 清空输入框并刷新问题列表
        questionInput.value = '';
        updateQuestionList();
    } else {
        alert('添加问题失败');
    }
});

async function updateQuestionList() {
    const response = await fetch('http://localhost:3030/questions');
    const questions = await response.json();
    const questionList = document.getElementById('question-list');
    questionList.innerHTML = '';
    questions.forEach(question => {
        const li = document.createElement('li');
        li.textContent = question;
        questionList.appendChild(li);
    });
}

updateQuestionList();

现在,你可以运行Rust后端服务器(cargo run),然后在浏览器中打开index.html文件,即可看到一个简单的问题记录系统。请注意,这个示例仅用于演示目的,实际应用中需要考虑数据持久化、错误处理等问题。


原文地址:https://blog.csdn.net/ChailangCompany/article/details/142601797

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!