Javascript 有一个go web服务接收帖子,但不清楚如何将响应发送回jquery
早上好 我有一些go代码,它接收json帖子并执行一些操作,但我想将结果或消息发送回jquery 包干管Javascript 有一个go web服务接收帖子,但不清楚如何将响应发送回jquery,javascript,jquery,json,ajax,go,Javascript,Jquery,Json,Ajax,Go,早上好 我有一些go代码,它接收json帖子并执行一些操作,但我想将结果或消息发送回jquery 包干管 import ( "fmt" "log" "net/http" "encoding/json" "os/exec" "strings" ) type Deploy struct { Environmentid string `json:"environmentid"` Versionid string `json:"versio
import (
"fmt"
"log"
"net/http"
"encoding/json"
"os/exec"
"strings"
)
type Deploy struct {
Environmentid string `json:"environmentid"`
Versionid string `json:"versionid"`
Dtp string `json:"dtp"`
}
func deploy(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin != "" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF- Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
if req.Method == "POST" {
d := Deploy{}
err := json.NewDecoder(req.Body).Decode(&d)
if err != nil {
panic("Can't decode Json received in post")
}
fmt.Println("Deploy: " + d.Environmentid + "," + d.Versionid + "," + d.Dtp)
// Run command
cmd := exec.Command("/bin/myscript.sh", strings.Split(fmt.Sprintf("-e %s -v %s", d.Environmentid, d.Versionid), " ")...)
cmdOut, cmdErr := cmd.Output()
if cmdErr != nil {
panic(cmdErr)
}
fmt.Println(string(cmdOut))
}
我现在拥有的jquery:
$.ajax({
type: 'POST',
url: url,
cache:false,
crossDomain: true,
contentType: 'application/json; charset=utf-8',
data: jsonData,
dataType: 'json',
success:function(result) {
$('#target').html('Request was sent successfully...');
console.log(result);
},
error:function(xhr,status,error) {
//alert(error);
}
});
我看到我发送的三件东西都很好。我想我看到了一些对$.ajax的回调选项的引用。我猜这允许我输入一个函数名来接收响应。请举例说明如何从go服务器接收具有成功或错误的json响应,以及如何将响应从go服务器发送到此回调。在您的
ajax
调用中,您已经指定了一个回调来接收响应;这就是success
,它将接收服务器的http.ResponseWriter
提供的数据
如果您的意思是,在http请求/响应周期完成后,您希望服务器稍后向客户端发送消息,那么您需要查看WebSocket。在您的
ajax
调用中,您已经指定了一个回调来接收响应;这就是success
,它将接收服务器的http.ResponseWriter
提供的数据
如果您的意思是,在http请求/响应周期完成后,您希望服务器稍后向客户端发起一条消息,那么您需要查看WebSocket。我使用以下内容:
func ajaxResponse(w http.ResponseWriter, res map[string]string) {
// set the proper headerfor application/json
w.Header().Set("Content-Type", "application/json")
// encode your response into json and write it to w
err := json.NewEncoder(w).Encode(res)
if err != nil {
log.Println(err)
}
}
func apiFunc(w http.ResponseWriter, r *http.Request) {
// do stuff
ajaxResponse(w, map[string]string{"data": "your data here"})
}
这样称呼它:
func ajaxResponse(w http.ResponseWriter, res map[string]string) {
// set the proper headerfor application/json
w.Header().Set("Content-Type", "application/json")
// encode your response into json and write it to w
err := json.NewEncoder(w).Encode(res)
if err != nil {
log.Println(err)
}
}
func apiFunc(w http.ResponseWriter, r *http.Request) {
// do stuff
ajaxResponse(w, map[string]string{"data": "your data here"})
}
编辑:
在客户端上,我使用不带jquery的“纯”ajax:
// a function to send user info to add them to a database
function addUser() {
// new request
var xhr = new XMLHttpRequest();
// type (eg POST, GET, etc), and api endpoint
xhr.open('POST', '/api/addUser');
// tell it you're sending json
xhr.setRequestHeader('Content-Type', 'application/json');
// call this function on load
xhr.onload = function() {
// if it was successful
if (xhr.status === 200) {
// parse the response into json
var userInfo = JSON.parse(xhr.responseText);
// use the json to change your apps UI
document.getElementById("footer").innerHTML = userInfo.error;
}
};
xhr.send(JSON.stringify({
// user info here
error: "nil"
}));
}
我用这样的方式:
func ajaxResponse(w http.ResponseWriter, res map[string]string) {
// set the proper headerfor application/json
w.Header().Set("Content-Type", "application/json")
// encode your response into json and write it to w
err := json.NewEncoder(w).Encode(res)
if err != nil {
log.Println(err)
}
}
func apiFunc(w http.ResponseWriter, r *http.Request) {
// do stuff
ajaxResponse(w, map[string]string{"data": "your data here"})
}
这样称呼它:
func ajaxResponse(w http.ResponseWriter, res map[string]string) {
// set the proper headerfor application/json
w.Header().Set("Content-Type", "application/json")
// encode your response into json and write it to w
err := json.NewEncoder(w).Encode(res)
if err != nil {
log.Println(err)
}
}
func apiFunc(w http.ResponseWriter, r *http.Request) {
// do stuff
ajaxResponse(w, map[string]string{"data": "your data here"})
}
编辑:
在客户端上,我使用不带jquery的“纯”ajax:
// a function to send user info to add them to a database
function addUser() {
// new request
var xhr = new XMLHttpRequest();
// type (eg POST, GET, etc), and api endpoint
xhr.open('POST', '/api/addUser');
// tell it you're sending json
xhr.setRequestHeader('Content-Type', 'application/json');
// call this function on load
xhr.onload = function() {
// if it was successful
if (xhr.status === 200) {
// parse the response into json
var userInfo = JSON.parse(xhr.responseText);
// use the json to change your apps UI
document.getElementById("footer").innerHTML = userInfo.error;
}
};
xhr.send(JSON.stringify({
// user info here
error: "nil"
}));
}
我最终更改了go服务器代码,并在客户端网页中添加了一个.ajaxSetup选项以禁用缓存和异步。JavaScriptURL进行了更改,以适应他们的示例如何使用带有参数的post,以便它可以存储post信息数组。如果需要,这将允许我添加一个GET来检索特定请求的信息 我的最后一个挑战是,当响应返回到网页时,它会在屏幕上闪烁一秒钟,然后重新设置页面。我如何获得结果以留在屏幕上并在列表框中保留响应?我已经有一段时间没有写一页了 注意:我担心的是,我不得不使用不推荐使用的异步缓存,因为ajax充其量只是间歇性的(也就是说,如果我尝试在没有异步和缓存选项的情况下发送几次,它不会等待结果,甚至不会让json进入服务器)
$.ajaxSetup({async: false, cache: false});
$.ajax({
type: 'POST',
url: url,
crossOrigin: true,
contentType: 'application/json',
data: jsonData,
dataType: 'json',
success: function(data) {
console.log(JSON.stringify(data))
document.getElementById("target").innerHTML = "<p>" + JSON.stringify(data) + "</p>";
alert(JSON.stringify(data));
},
error: function(data) {
console.log(JSON.stringify(data));
}
});
最后,我更改了go服务器代码,并在客户端网页中添加了一个.ajaxSetup选项,以禁用缓存和异步。javascript url已更改,以适应他们使用带有参数的post的方式,以便它可以存储post信息数组。这将允许我添加一个GET来检索特定请求的信息,如果我艾瑞德 我的最后一个挑战,也许你可以帮助,是当响应返回到网页时,它会在屏幕上闪烁一秒钟,然后重新设置页面。我如何获得结果以留在屏幕上并将响应保留在列表框中?我创建页面已经有一段时间了 注意:我担心的是,我不得不使用不推荐使用的异步缓存,因为ajax充其量只是间歇性的(也就是说,如果我尝试在没有异步和缓存选项的情况下发送几次,它不会等待结果,甚至不会让json进入服务器)
$.ajaxSetup({async: false, cache: false});
$.ajax({
type: 'POST',
url: url,
crossOrigin: true,
contentType: 'application/json',
data: jsonData,
dataType: 'json',
success: function(data) {
console.log(JSON.stringify(data))
document.getElementById("target").innerHTML = "<p>" + JSON.stringify(data) + "</p>";
alert(JSON.stringify(data));
},
error: function(data) {
console.log(JSON.stringify(data));
}
});
这是您的回调:
success:function(result){$('#target').html('请求已成功发送…');console.log(result);}
-结果应该是您的JSON,但我看不到服务器返回JSONI我不确定您从myscript.sh
中的输出是什么样子,但作为一个初学者,您可以尝试将其发送回。与其使用fmt.Println(string(cmdOut))
打印到stdout,不如尝试fmt.Fprint(rw,string(cmdOut))
这是流式响应吗?在这种情况下,当我的脚本运行时,它能否说“开始运行…”并将其转到网页上,然后让它在完成时说最后一条消息,这是一堆东西(即,不只是说完成的消息)。就像Mark在下面建议的那样,查看WebSocket。出于某种原因,它会抛出错误:error,我看到go服务器没有显示它收到了post json数据。如果我再次运行它,它不会抛出错误,但当go服务器到达末尾并写入ftm.Fprint(rw,string(cmdOUt)),我没有在网页上看到任何我认为会转到网页和console.log的内容。这是您的回调:success:function(result){$('#target').html('请求已成功发送…');console.log(result);}
-结果应该是您的JSON,但我看不到服务器返回JSONI我不确定您从myscript.sh
中的输出是什么样子,但作为一个初学者,您可以尝试将其发送回。与其使用fmt.Println(string(cmdOut))
打印到stdout,不如尝试fmt.Fprint(rw,string(cmdOut))
这是流式响应吗?在这种情况下,当我的脚本运行时,它能否说“开始运行…”并将其转到网页上,然后让它在完成时说最后一条消息,这是一堆东西(即,不只是说完成的消息)。就像Mark在下面建议的那样,查看WebSocket。出于某种原因,它会抛出错误:error,我看到go服务器没有显示它收到了post json数据。如果我再次运行它,它不会抛出错误,但当go服务器到达末尾并写入ftm.Fprint(rw,string(cmdOUt)),我没有在网页上看到任何我认为会转到网页和console.log的内容。好的,我需要先解决一些问题。为什么这段代码会立即转到:{“readyStat”