Html语言中带有fetch方法的Onclick回调

wqlqzqxt  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(128)

我有以下HTML代码:

<!doctype html>
<html>

<head>
    <title>Online Strategy</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="codemirror/lib/codemirror.css">
    <script src="codemirror/lib/codemirror.js"></script>
    <script src="codemirror/addon/mode/simple.js"></script>
    <script src="codemirror/mode/rust/rust.js"></script>
    <link rel="stylesheet" href="codemirror/theme/dracula.css">
</head>

<body>
    <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
    <form action='/result' method=POST target="dummyframe">
        <textarea id="editor" name="name"></textarea>
        <button onclick=GetData()>Run</button>
    </form>
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
            lineNumbers: true,
            lineWrapping: true,
            indentUnit: 2,
            tabsize: 2,
            indentWithTabs: 1,
            mode: "rust",
            theme: "dracula",
        });
        editor.setSize(700, 700);
        editor.scrollTo(700, 700);

        async function GetData() {
            console.log("my ssss");
            fetch("http://127.0.0.1:8081/result", { method: "POST" })
                .then((response) => {
                    var upperCase = response.json();
                    console.log("dddd");
                    // var upperCase = upperCase.toUpperCase();
                    // document.getElementById("outputText").innerHTML = upperCase;
                })
                .then((response) => {
                    console.log("gggg");
                    setStatusMessage(response.status);
                })
                .catch(() => {
                    console.log("zzz");
                    setStatusMessage("ERROR");
                })
        }
    </script>

    <h3>INPUT</h3>
    <textarea id="inputText" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
    <button onclick="MakeUpper()">Enter</button>
    <h3>OUTPUT</h3>
    <textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>
    <script>
        function MakeUpper() {
            var upperCase = document.getElementById("inputText").value;
            var upperCase = upperCase.toUpperCase();
            document.getElementById("outputText").innerHTML = upperCase;
        }
    </script>

</body>

</html>

我正在尝试做的如下:
1.我在第一个文本区域输入一些文本,然后我点击Run按钮,然后在url 127.0.0.1/result中,将有一个响应。
1.我获取响应,并将正文粘贴到第二个文本区域。
但它并没有像预期的那样工作,它有错误404 not found
我做错了什么?
服务器端是这样的:

#![allow(unused_imports)]

use std::time;

use actix_web::{
    middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result,
    get,
    post,
    http::{
        header::{self ,ContentType},
        Method, StatusCode,
    }
};
use actix_files::Files;
use serde::{Serialize, Deserialize};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_html)
            .service(show_result)
    })
    .bind(("127.0.0.1", 8081))?
    .run()
    .await
}

#[get("/")]
async fn get_html() -> impl Responder {
    HttpResponse::Ok()
        .content_type("text/html")
        .body(include_str!("../form2.html"))
}

#[post("/result")]
async fn show_result(params: web::Form<InputCodes>) -> impl Responder {
    let mut res = format!("your input is {}, and I have got it in {:?}", params.name, time::Instant::now());
    HttpResponse::Ok()
        .content_type("text/plain")
        .body(res)
}

#[derive(Serialize, Deserialize)]
pub struct InputCodes {
    pub name: String
}

函数show_result处理表单post,并在/result网页中写入一些单词。

nwsw7zdq

nwsw7zdq1#

如果你想使用自定义获取来提交表单。你不需要actionmethod属性。

<form id="getData">
  <textarea id="editor" name="name"></textarea>
  <button type="submit">Run</button>
</form>
async function GetData(event) {
  // event.target is reference to the form element
  const data = new FormData(event.target); // Get all input data

  fetch("http://127.0.0.1:8081/result", {
      method: "POST",
      body: data, // Send body
    })
    .then((response) => {
      var upperCase = response.json();
      console.log("dddd", upperCase);
      // var upperCase = upperCase.toUpperCase();
      // document.getElementById("outputText").innerHTML = upperCase;
    })
    .then((response) => {
      console.log("gggg");
      setStatusMessage(response.status);
    })
    .catch(() => {
      console.log("zzz");
      setStatusMessage("ERROR");
    })
}

const form = document.getElementById("getData")

form.addEventListener("submit", (event)=>{
  event.preventDefault()

  GetData(event)
})

相关问题