【发布时间】:2011-06-26 10:57:06
【问题描述】:
我正在使用 Go 编程语言运行服务器,当我在浏览器中加载服务器时,会调用 temp 处理程序函数,并且 getjson.html 文件由该 temp Handler 函数提供服务。现在屏幕显示“获取 Json 数据”按钮。单击此按钮后,我没有得到任何结果(因为应该在屏幕上显示某些内容)。
我检查了 javascript 控制台,没有任何错误。 我无法弄清楚问题是什么,为什么屏幕上没有任何输出。
servejson.go 的内容:
package main
import (
"http"
"flag"
)
var path = flag.String("root", "/home/chinmay/work/json/getjson.html", "Set root directory, use absolute path")
func temp(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
http.ServeFile(w,r,*path)
}
func main(){
http.HandleFunc("/",temp)
http.ListenAndServe(":8080", nil)
}
getjson.html 的内容:
package main
import (
"http"
"flag"
)
var path = flag.String("root", "/home/chinmay/work/json/getjson.html", "Set root directory, use absolute path")
func temp(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "text/html")
http.ServeFile(w,r,*path)
}
func main(){
http.HandleFunc("/",temp)
http.ListenAndServe(":8080", nil)
}
json_data.js 的内容:
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
【问题讨论】:
-
是的,这应该是可能的 -
getJSON()应该这样做,即使文本文件的内容类型是text/plain。我不完全确定,但为什么不简单地尝试一下? -
您是否尝试从本地机器读取文本文件?我不相信这在 js 中是可能的
-
实际上我正在运行一个服务器,然后我会提供这个包含 js 脚本的 html 文件,然后它会尝试访问 file.txt 以获取 json 数据并将其打印到屏幕上。跨度>
-
@chinmay:没关系,前提是
json.txt可以通过 HTTP 访问并且(使用您提供的路径)是运行此代码的文档的对等点(例如,http://example.com/page.html和http://example.com/json.txt)。 -
你能告诉我为什么我上面给出的代码没有运行吗,它遵循你所说的!但是,正如您在示例中向我展示的那样,我无法获得任何输出。您没有访问文件,而我正在尝试访问 json.txt 文件,您能以这个角度向您展示示例吗?
标签: javascript json go