0
웹 개발, Go 및 Ajax 학습으로 시작하고 있지만 잘못된 점을 보면서 문제가 발생했습니다. 나는 단순히 클라이언트와 서버간에 데이터를주고 받는다. Ajax 요청을 사용하면 양식의 데이터를 서버로 보냈지 만 로그에서 "posthandler"가 인쇄되지 않기 때문에 서버에 도달하지 못하는 것 같아서 ajax 요청에 문제가 있다고 생각하게됩니다. 모든 관련 코드가있는 main.go, index.html 및 js/getData.js가 첨부됩니다.Ajax 요청 웹 서버로 이동하지 않음
main.go
package main
import (
"fmt"
"net/http"
"io/ioutil"
"log"
)
var INDEX_HTML []byte
func main(){
fmt.Println("starting server on http://localhost:8888/\nvalue is %s", value)
http.HandleFunc("/", IndexHandler)
http.HandleFunc("/post", PostHandler)
http.ListenAndServe(":8888", nil)
}
func IndexHandler(w http.ResponseWriter, r *http.Request){
log.Println("GET /")
w.Write(INDEX_HTML)
}
func PostHandler(w http.ResponseWriter, r *http.Request){
r.ParseForm()
log.Println("in posthandler", r.Form)
var value = r.FormValue("textfield")
w.Write([]byte(value))
}
func init(){
INDEX_HTML, _ = ioutil.ReadFile("./html/index.html")
}
index.html을
<!doctype html>
<html>
<head>
<title>Page Title</title>
<script src="js/getData.js"></script>
</head>
<body>
<form action="/post" method="post">
<textarea type="text" name="input" id="textfield"></textarea>
<br />
<input type="submit" name="button" id="button" value="Send" onclick="loadXMLDoc()"/>
</form>
<div id="fromserver">
</div>
</body>
</html>
JS/getData.js
function loadXMLDoc() {
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("fromserver").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","post",true);
xmlhttp.send();
}
JS 기능은 이제 posthandler에 보낼 않고 이제 URL 변경 localhost로 : 8888/post하지만 페이지가 비어 있습니다. 어떻게하면 클라이언트가 div id = "fromserver"가 아약스 호출의 데이터로 변경되는 동일한 페이지에서 말하도록 할 수 있습니까? 또한 jquery 파일을 많이 사용하는 경우 모든 파일에 대해 singleServe() 사용해야합니까? – irregular
jquery에 대해'http.Handle ("/ jquery", http.FileServer (http.Dir ("/ path/to/jquery"))))' – ain
과 같은 임의의 dir에있는 모든 파일을 제공하는 hadler를 추가 할 수 있습니다. @ user2807904, 귀하의 초기 질문을 기반으로, 나는 당신이 그것을 작동하게하고 무엇이 잘못되었는지 이해할 필요가 있다고 가정합니다. 어쨌든이 [link] (http://stackoverflow.com/a/14086560/2171928)를 읽으면 정적 자산을 어떻게 렌더링 할 수 있는지 이해할 수 있습니다. –