我正在使用Go,JavaScript和PostgreSQL开发Web应用程序。
我将Go程序与数据库链接没有任何问题。但是我在使用JavaScript时遇到了一些问题。
这是我的Go代码,该代码连接到数据库并在我调用localhost:8080
时返回表的随机元素:
type Quote struct {
ID int
Phrase string
Author string
}
var db *sql.DB
func init() {
var err error
db, err = sql.Open("postgres", "postgres://gauthier:password@localhost/quotes?sslmode=disable")
if err != nil {
panic(err)
}
if err = db.Ping(); err != nil {
panic(err)
}
fmt.Println("You connected to your database")
}
func getQuotes(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
rows, err := db.Query("SELECT id, phrase, author FROM citations ORDER BY RANDOM() LIMIT 1;")
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
defer rows.Close()
quotations := make([]Quote, 0)
for rows.Next() {
qt := Quote{}
err := rows.Scan(&qt.ID, &qt.Phrase, &qt.Author)
if err != nil {
panic(err)
}
quotations = append(quotations, qt)
}
if err = rows.Err(); err != nil {
panic(err)
}
for _, qt := range quotations {
payload, _ := json.Marshal(qt)
w.Header().Add("Content-Type", "application/json")
w.Write(payload)
}
}
func main() {
http.HandleFunc("/", getQuotes)
http.ListenAndServe(":8080", nil)
}
当我运行该程序并使用curl -i localhost:8080
时,它将返回我期望的结果,即数据库中的随机引号
`gauthier@gauthier-Latitude-7280:~/gocode/sprint0$ curl -i localhost:8080
HTTP/1.1 200 OK
Content-Type: application/json
Date: Thu, 30 Aug 2018 12:28:00 GMT
Content-Length: 116
{"ID":7,"Phrase":"I've never had a problem with drugs. I've had problems with the police","Author":"Keith Richards"}`
现在,当我尝试发出相同的请求但使用JavaScript而不是使用那个小脚本的curl时:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random quote</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function getQuotations() {
httpRequest= new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
alertContents(httpRequest)
};
httpRequest.open("GET", "http://localhost:8080", true);
}
function alertContents(httpRequest) {
console.log("http status: "+httpRequest.status);
console.log("http response: "+httpRequest.responseText);
}
</script>
<button onclick="getQuotations()">Click here for a quotation</button>
</body>
</html>
当我单击按钮并打开Chromium的控制台时,我得到:
http status: 0 hello.html:18
http response: hello.html:19
有人可以帮我吗?
答案 0 :(得分:0)
尝试使用XMLHttpRequest有所不同,以便使用load事件:
httpRequest= new XMLHttpRequest();
httpRequest.load= function() {
alertContents(this.responseText)
};
httpRequest.open("GET", "http://localhost:8080", true);
httpRequest.send();
答案 1 :(得分:0)
如果您对Promises感到满意,可以使用include('./connect_local_pdo.php'); //Includes DB Connection Script
简化此操作。您不必处理fetch
和readystatechange
等代码,这是一个示例。
status