gpt4 book ai didi

ajax - HTML文档发出AJAX请求,服务器接收然后发送回数据

转载 作者:行者123 更新时间:2023-12-01 22:08:27 27 4
gpt4 key购买 nike

这个想法是要有一个index.html,它通过Apache Web服务器提供服务,以将数据发送到IP地址和端口(AJAX),并等待随后显示的响应。用GO编写的“数据”服务器等待接收数据,然后通过AJAX发送一些数据。

但是以某种方式这不起作用并且不会生成输出:

index.html:

<html>
<head>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
</head>
<body>

<script>
$(document).ready(function () {
$('#button1').click(function () {
$.ajax({
url: '127.0.0.1:8888/receive',
type: 'post',
dataType: 'html',
data : { post_data: 'hello world'},
success : function(data) {
$('#div1').html(data);
},
});
});
});
</script>

<div id='div1'>
<h3>before</h3>
</div>

<input id='button1' type='button' value='AJAX POST to golang server'>

</body>
</html>

server.go:
package main

import (
"fmt"
"net/http"
)

func receiveAjax(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
data := r.FormValue("post_data")
fmt.Println("Receive ajax post data string ", data)
w.Write([]byte("<h2>after<h2>"))
}
}

func main() {
mux := http.NewServeMux()
mux.HandleFunc("/receive", receiveAjax)

http.ListenAndServe(":8888", mux)
}

最佳答案

127.0.0.1:8888/receive不是有效的网址(您Javascript中的AJAX调用失败,出现SyntaxError: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL",但您没有捕获到该错误)。在AJAX调用中添加error函数可以更轻松地发现此类问题(浏览器开发工具也是如此)。

以下内容使用http://127.0.0.1:8888/receive对我有用(请注意,我正在通过go应用程序提供javascript,以简化操作并避免CORS问题-从Apache提供页面时,您可能会收到其他错误,但至少您应该能够看到正在运行的内容浏览器控制台中的错误)。

package main

import (
"fmt"
"net/http"
)

const html = `<html>
<head>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
</head>
<body>

<script>
$(document).ready(function () {
$('#button1').click(function () {
$.ajax({
url: 'http://127.0.0.1:8888/receive',
type: 'post',
dataType: 'html',
data : { post_data: 'hello world'},
error : function(err) {
console.log(err);
},
success : function(data) {
$('#div1').html(data);
},
});
});
});
</script>

<div id='div1'>
<h3>before</h3>
</div>

<input id='button1' type='button' value='AJAX POST to golang server'>

</body>
</html>`

func receiveAjax(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
data := r.FormValue("post_data")
fmt.Println("Receive ajax post data string ", data)
w.Write([]byte("<h2>after<h2>"))
}
}

func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(html)) })
mux.HandleFunc("/receive", receiveAjax)

http.ListenAndServe(":8888", mux)
}

关于ajax - HTML文档发出AJAX请求,服务器接收然后发送回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479839/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com