Reputation: 1403
I have a .txt file which contains 3d points of the form (x,y,z). Using go I extract the point co-ordinates into arrays X[], Y[], Z[]. Now I need to pass these arrays to an external javascript (ie a function in js). How do I do this? In general, how do I pass some arguments to any js function in a .html file.
Upvotes: 0
Views: 1312
Reputation: 122888
I'd say: just pass them (by reference):
function doSomethingWithPpoints(x,y,z){
//do something with for example x[0], y[1] etc.
}
//later on
doSomethingWithPoints(points1,points2,points3);
[edit] This may be an idea: serialize the array to string an attach that as a querystring to the url:
var url = 'http://somesite.net/somefile.html'+
'?points1=1,2,3&points2=3,2,1&points35,6,7';
Now in the javascript of somefile.html extract the arrays like this:
var qstr = location.href.split('?')[1],
points = qstr.split('&')
pointsObj = {},
i = 0;
while ((i = i + 1)<points.length) {
var point = points[i].split('=');
pointsObj[point[0]] = point[1].split(',');
}
this should deliver the Object pointsObj
with 3 properties (points1-3) with array values
//pointsObj looks like this
{ points1: [1,2,3],
points2: [3,2,1],
points3: [5,6,7] }
Upvotes: 2
Reputation: 26370
Assuming that the server you are running is a Go program, you should go the other way around.
The javascript function performs an XHR request to the server, asking for the vector data. The server then optionally reads them from the text file (or already has them in-memory) and sends the data encoded as json back to the client.
index.html:
The 'doXHR' method should do the actual get request to the server. Whatever the implementation of that is, is up to you to figure out. The jquery framework has a $.ajax() method for this very purpose.
function getData() {
doXHR({
uri: "/getvectors",
success: function(data) {
// data now holds the json encoded vector list.
// Do whatever you want with it here.
}
});
}
On the Go side:
func myVectorHandler(w http.ResponseWriter, r *http.Request) {
var vectors struct {
X []float32
Y []float32
Z []float32
}
// Fill the X/Y/Z slices here.
// Encode it as json
var data []byte
var err os.Error
if data, err = json.Marshal(vectors); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
// Set the correct content type and send data.
w.Headers().Set("Content-Type", "application/x-json");
w.Write(data);
}
A much simpler solution is to store the vector data in json format in the textfile and serve it to the client as-is. That way your Go server does not have to perform the conversion at runtime.
Upvotes: 0