I am running a server with Go programming language, and when I load the server in the browser, the temp handler function is called and the getjson.html file is served by this temp Handler function. Now the screen shows a “Get Json Data” button. On clicking this button, I am not getting any results (as something should be displayed on the screen).
I checked the javascript console and there are no errors as such.
I am not able to figure out what the problem is, why isn’t there any output on the screen.
Contents of 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)
}
Contents of 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)
}
Contents of json_data.js:
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
Yes, you can. Live example. Provided that
json.txtis a resource next to the document in which this code is running, and (on some browsers) provided this is not running from a local file (e.g., afile://URL rather than anhttp://one; some browsers are okay with local files accessing other local files via ajax, others are not).A couple of notes:
In the
line,
fieldwill be the value of each property (e.g., “John”).So for this specific example, you’d probably be better off with
Live example
Update: From your comments on another answer, it seems like you might be unclear on where and how the script code is running. The JavaScript script runs on the client’s browser. The path to use to reference
json.txtis exactly like (say) the path to an image you want to show on a page.json.txtmust be accessible via the web server, just like an image would need to be accessible via the web server. Think ofjson.txtas just another resource used by your web page, like any other. In terms of the path, and how you have to makejson.txtavailable, the same rules apply. To be clear: Script running client-side in a web page cannot access a server-side file that can’t be retrieved by the browser.Update 2: You’ve posted more code, and it looks like you’ve made your server only serve the
getjson.htmlfile. Your server also has to serve thejson.txtfile, or the browser can’t access it.