通过go将数组传递给外部js

huangapple go评论116阅读模式
英文:

Passing an array to an external js through go

问题

我有一个包含形式为(x,y,z)的3D点的.txt文件。
使用go语言,我将点坐标提取到数组X [],Y [],Z []中。
现在我需要将这些数组传递给外部的javascript(即js中的一个函数)。
我该如何做到这一点?
一般来说,我如何将一些参数传递给.html文件中的任何js函数。

英文:

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.

答案1

得分: 2

我会说:只需通过引用将它们传递:

function doSomethingWithPpoints(x,y,z){
   //对例如x[0]、y[1]等进行操作
}
//稍后
doSomethingWithPoints(points1,points2,points3);

[编辑] 这可能是一个主意:将数组序列化为字符串,并将其作为查询字符串附加到URL上:

var url = 'http://somesite.net/somefile.html'+
          '?points1=1,2,3&points2=3,2,1&points35,6,7';

现在在somefile.html的javascript中提取数组,像这样:

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(',');
    }

这应该返回具有3个属性(points1-3)和数组值的对象pointsObj

//pointsObj看起来像这样
{ points1: [1,2,3],
  points2: [3,2,1],
  points3: [5,6,7] }
英文:

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);

[<b>edit</b>] This may be an idea: serialize the array to string an attach that as a querystring to the url:

var url = &#39;http://somesite.net/somefile.html&#39;+
          &#39;?points1=1,2,3&amp;points2=3,2,1&amp;points35,6,7&#39;;

Now in the javascript of somefile.html extract the arrays like this:

var qstr = location.href.split(&#39;?&#39;)[1],
    points = qstr.split(&#39;&amp;&#39;)
    pointsObj = {},
    i = 0;
    while ((i = i + 1)&lt;points.length) {
      var point = points[i].split(&#39;=&#39;);
      pointsObj[point[0]] = point[1].split(&#39;,&#39;);
    }

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] }

答案2

得分: 0

假设你正在运行的服务器是一个Go程序,你应该采取另一种方式。

javascript函数执行一个XHR请求到服务器,请求向量数据。服务器可以选择从文本文件中读取它们(或者已经将它们保存在内存中),然后将数据编码为json格式发送回客户端。

index.html:

'doXHR'方法应该执行实际的get请求到服务器。具体实现取决于你自己去找出来。jquery框架有一个$.ajax()方法专门用于此目的。

 function getData() {
      doXHR({
           uri: &quot;/getvectors&quot;, 
           success: function(data) {
                // data现在保存了json编码的向量列表。
                // 在这里可以对它做任何你想做的事情。
           }
      });
 }

Go端:

 func myVectorHandler(w http.ResponseWriter, r *http.Request) {
      var vectors struct {
           X []float32
           Y []float32
           Z []float32
      }
      
      // 在这里填充X/Y/Z切片。

      // 将其编码为json
      var data []byte
      var err os.Error
      if data, err = json.Marshal(vectors); err != nil {
           http.Error(w, err.String(), http.StatusInternalServerError)
           return
      }

      // 设置正确的内容类型并发送数据。
      w.Headers().Set(&quot;Content-Type&quot;, &quot;application/x-json&quot;);
      w.Write(data);
 }

一个更简单的解决方案是将向量数据以json格式存储在文本文件中,并将其原样提供给客户端。这样,你的Go服务器就不需要在运行时执行转换。

英文:

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: &quot;/getvectors&quot;, 
           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(&quot;Content-Type&quot;, &quot;application/x-json&quot;);
      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.

huangapple
  • 本文由 发表于 2011年6月14日 15:00:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/6340116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定