Fiber Web框架出现ajax请求无法发送的问题
时间:2024-03-04
浏览:264
作者:佚名
学习Golang要努力,但是不要急!今天的这篇文章《Fiber Web框架出现ajax请求无法发送的问题》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
请原谅我,但我不太懂英语。我使用翻译器deepl.com。此时俄罗斯程序员无法帮助我。 我不是程序员,“我只为自己编程”。我遇到问题 - 我无法向服务器发送 post (json) 请求。
我想要做什么 - fiber 的服务器通过 post 请求(json、xmlhttprequest)从 html 页面获取 2 个参数,并在处理后服务器给我一个字符串。 我使用 fiber 是因为我曾经为自己制作过一个小型静态站点,并且“示例”中的内容都很清楚。我快速执行了 ctrl+c - ctrl+v,只是调整了我的代码。然后我调整了html、js、css。我有一个工作网站! :-)
main.go - 启动服务器(这里没有问题)
package main
import (
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/middleware/logger"
)
func main() {
app := fiber.new()
app.use(logger.new())
app.static("/", ".")
app.get("/", func(c *fiber.ctx) error {
return c.sendfile("./main.html")
})
app.post("/search", posttodo)
app.listen(":3003")
}
search.go - 接收数据后要做什么的逻辑。 (到目前为止只是一种模板,有一个小问题,但基本上可以工作)。
package main
import (
"fmt"
"github.com/gofiber/fiber"
)
type response_json struct {
name string `json:"name"`
surname string `json:"surname"`
}
func posttodo(c *fiber.ctx) error {
type request struct {
name string `json:"name"`
surname string `json:"surname"`
}
var body request
err := c.bodyparser(&body)
if err != nil {
return c.status(fiber.statusbadrequest).json(fiber.map{
"error": "cannot parse json",
})
}
fmt.println("body: ", err)
todo := response_json{
name: body.name,
surname: body.surname,
}
fmt.println("todo: ", todo)
my_request := "<div>" + todo.name + "</div>"
my_request = my_request + "<hr><div>" + todo.surname + "</div>"
return c.sendstring(my_request)
}
main.html - 主页
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>proba</title>
</head>
<body>
<div class="container">
<div class="logo">
<h1>proba</h1>
</div>
<form action="/search" class="search_form" method="post">
<div class="search">
<input type="text" id="search_name" value="" name="search_name" placeholder="search name...">
<input type="text" id="search_surname" value="" name="search_surname" placeholder="search surname...">
<input type="submit" id="send" class="search_button" value="go">
</div>
</form>
<div id="result" class="result">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
main.js - 单击后处理表单的脚本(主要问题在这里)
let mybutton = document.getelementbyid("send");
mybutton.addeventlistener("click", () => {
let name = document.getelementbyid("search_name").value;
let surname = document.getelementbyid("search_surname").value;
let s = {};
s.name = `${name}`;
s.surname = `${surname}`;
let search_json = json.stringify(s);
console.log("s: ", s);
console.log("name: ", name);
console.log("surname: ", surname);
console.log("search_json ", search_json);
let request = new xmlhttprequest();
request.open('post','/search');
request.setrequestheader('content-type', 'application/json');
request.onreadystatechange = function () {
if (request.readystate == 4 && request.status == 200)
document.getelementbyid("result").innerhtml=request.responsetext;
}
request.send(search_json);
});
main2.js - 一个无需“点击”即可工作的试用版 js(通过它我试图了解问题出在哪里)
let user = {
name: "Ivan",
surname: "Ivanov"
};
console.log("user:", user);
let json = JSON.stringify(user);
console.log("json:", json);
let request = new XMLHttpRequest();
request.open("POST", "/search");
request.setRequestHeader('Content-type', 'application/json');
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200)
document.getElementById("result").innerHTML=request.responseText;
}
request.send(json);
我有什么: 1 - 我启动服务器并转到 main.html。我填写数据并单击按钮(提交(go)),然后我看到了这个结果。请求未发送,而且奇怪的是 console.log("s: ", s); 行不起作用(控制台中的输出没有发生)。 在此输入图像描述
在此处输入图像描述
2 - 但是,如果您使用脚本 main2.js(该脚本在页面加载时立即运行),那么一切似乎都可以运行。数据发送出去,服务器处理后返回给我。 虽然,由于某种原因,在文件 search.go 中输出 fmt.println("body: ", err) - "nil",但在变量“body”中,根据文档解码了查询正文 (application/json)。
在此处输入图像描述
在此处输入图像描述
请帮我解决这个问题。我花了 2 天在 google、yandex、youtube 上寻找问题的解决方案,但找不到问题的解决方案。
我将提前感谢您的答复!
正确答案
您看到的问题与 go(甚至 fiber)无关,这是因为您的表单是立即发布的,javascript 没有机会触发。
您需要添加 preventdefault(); 以停止事件“冒泡”并触发表单提交。
// Bind the call to the variable 'e'
mybutton.addEventListener("click", (e) => {
// Add this line!
e.preventDefault();
/* ... the rest is the same ... */
今天关于《Fiber Web框架出现ajax请求无法发送的问题》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
