英文:
How to send data from the drop-down list to the server?
问题
我正在使用Go开发一个Web应用程序。我有一个下拉列表,它是从一个模板中生成的。
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">删除服务</button>
<ul id="myDropdown" class="dropdown-content">
{{range .}}
<li>{{.Id}}</li>
{{end}}
</ul>
</div>
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
操作逻辑如下:用户选择一个列表项 -> 选定的值必须传递给服务器以执行进一步的指令。
了解了这个问题后,我尝试首先在浏览器的控制台中输出数据:
var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
var targetEl = event.target;
console.log(targetEl.innerHTML)});
我做到了,但我不知道接下来该怎么做。
服务器代码如下所示:
func main() {
r := httprouter.New()
routes(r)
err := http.ListenAndServe("localhost:4444", r)
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
}
func routes(r *httprouter.Router) {
r.ServeFiles("/public/*filepath", http.Dir("public"))
r.GET("/", controller.StartPage)
r.GET("/auth", controller.LoginPage)
r.POST("/login", controller.Log_in)
r.POST("/add_uslugu", controller.Add_from_html)
}
英文:
I am developing a web application in Go. I have a drop-down list, it is formed from a template.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn"> Удалить услугу</button>
<ul id="myDropdown" class="dropdown-content">
{{range .}}
<li>{{.Id}}</li>
{{end}}
</ul>
</div>
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
The logic of the operation is as follows: the user selects a list item -> the selected value must be transmitted to the server to execute further instructions.
Understanding this problem, I tried to first output the data to the console in the browser:
var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
var targetEl = event.target;
console.log(targetEl.innerHTML)});
I did it, but I have no idea what to do next.
The server code is represented below:
func main() {
r := httprouter.New()
routes(r)
err := http.ListenAndServe("localhost:4444", r)
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
}
func routes(r *httprouter.Router) {
r.ServeFiles("/public/*filepath", http.Dir("public"))
r.GET("/", controller.StartPage)
r.GET("/auth", controller.LoginPage)
r.POST("/login", controller.Log_in)
r.POST("/add_uslugu", controller.Add_from_html)
}
答案1
得分: 1
你可以发送一个AJAX请求。在下面的代码块中,我获取了li
元素(而不是你所做的ul
),并为每个元素添加了一个点击监听器。我将li
的innerText
作为id
,然后发送一个带有id
参数的AJAX请求。我不知道这个请求应该发送到哪个路径,所以你需要用你自己的路径替换它。我也不确定你需要什么类型的请求,我这里是发送了一个POST请求。最后,我为你创建了一个回调函数,目前什么也没做,但你需要用它来处理服务器的响应。
var ul = document.querySelectorAll('ul > li');
for (let li of ul) {
li.addEventListener('click', function (event) {
let id = li.innerText;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// 在这里处理this.responseText的内容
}
};
xhttp.open("POST", "<yoururl>", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id=" + id);
});
}
英文:
You can send an AJAX request. In the code chunk below I'm getting the li
elements (not the ul
as you did) and add a click listener to each of them, I mine the id
as the innerText
of the li
and then sending an AJAX request, passing the id
. I'm not aware of the path where this needs to be sent, so you will need to replace the path with your own and I'm also unsure what type of request you need, I was doing a POST request. Finally, I created a callback function for you that currently does nothing, but you will need it to handle server responses.
var ul = document.querySelectorAll('ul > li');
for (let li of ul) {
li.addEventListener('click', function (event) {
let id = li.innerText;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Do something with this.responseText;
}
};
xhttp.open("POST", "<yoururl>", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id=" + id);
}
}
答案2
得分: 1
谢谢你的回答,我最终成功解决了这个问题,上面提出的方法可能更正确,但我想自己写出解决方法,也许对某人有帮助
首先,我们没有太多选项来从前端发送数据,需要编写一个处理JSON的处理程序。
type Service_struct struct {
Service_name string
}
func Add_service(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
var t Service_struct
body, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(body, &t)
if err != nil {
panic(err)
}
log.Println(t)
}
接下来,你需要注册从JavaScript发送数据。为此,导入axios客户端。
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
然后,我们编写发送数据的代码。
var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
var targetEl = event.target;
var serviceName = targetEl.innerHTML;
console.log(serviceName)
axios.post('/add_service', {
service_name: serviceName
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
完成了,现在我们可以在服务器应用程序中获取这些数据。
英文:
Thank you for your answer, I still managed to solve this problem, the method proposed above is probably more correct, but I want to write how I got to it myself, maybe it will help someone
Firstly , we don 't have so many options for sending data from the front, need to write a handler for processing json.
type Service_struct struct {
Service_name string
}
func Add_service(rw http.ResponseWriter, req *http.Request, p
httprouter.Params) {
var t Service_struct
body, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(body, &t)
if err != nil {
panic(err)
}
log.Println(t)
}
Next, you need to register sending data from js.To do this, import the axios client
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
After that, we prescribe the sending of data
var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
var targetEl = event.target;
var serviceName = targetEl.innerHTML;
console.log(serviceName)
axios.post('/add_service', {
service_name: serviceName
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Done, now we can get this in server app.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论