2011-06-14 62 views
0

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

+4

这与Java有什么关系? Java和Javascript是完全不同的语言。 – 2011-06-14 07:03:54

+0

Go和JavaScript之间的连接在哪里? Go是否调用JavaScript? Go是否提供JavaScript来源?你的环境是什么样的? – Kissaki 2011-06-15 20:05:13

+0

其实,我正在运行一个服务器,我必须从这个服务器调用一个javascript函数,并且传递的参数也是由go生成的。现在主要的问题是如何使这些参数在js函数中生成.... – chinmay 2011-06-17 14:21:28

回答

0

假设你正在运行的服务器是一个围棋程序,你应该围绕走另一条路。

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

的index.html:

的 'doXHR' 的方法应该做实际的GET请求到服务器。无论执行什么,都取决于你自己。 jquery框架有一个$ .ajax()方法用于这个目的。

function getData() { 
     doXHR({ 
      uri: "/getvectors", 
      success: function(data) { 
       // data now holds the json encoded vector list. 
       // Do whatever you want with it here. 
      } 
     }); 
} 

在转到侧:

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

一个更简单的解决方案是JSON格式的矢量数据存储在文本文件,并将其用于将客户端原样。这样你的Go服务器就不必在运行时执行转换。

+0

非常感谢,这真的非常有用 – chinmay 2011-06-17 14:20:44

+0

更简单的解决方案是将矢量数据存储在json格式在文本文件中并按原样提供给客户端。这样你的Go服务器就不必在运行时执行转换。你能告诉我这是怎么做到的? – chinmay 2011-06-24 11:24:14

+0

有没有什么作为一个.json文件,我可以以json格式存储数据,然后当用户需要时,javascript会传递这个.json文件的内容....您可以发布一些链接以供参考.. – chinmay 2011-06-24 11:28:12

1

我说:只是通过它们(通过参考):

function doSomethingWithPpoints(x,y,z){ 
    //do something with for example x[0], y[1] etc. 
} 
//later on 
doSomethingWithPoints(points1,points2,points3); 

[编辑]这可能是一个想法:该阵列serialeze串附着,作为查询字符串的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 looks like this 
{ points1: [1,2,3], 
    points2: [3,2,1], 
    points3: [5,6,7] } 
+0

这很可能。那么也许换一个问题来澄清一下可能会增强我的理解? – KooiInc 2011-06-14 08:06:04

+0

我不认为你知道我在问什么,我说的是我有一个文件“main.go”,其中我写了代码来提取数组x [],y [],z []从一个.txt文件。从.txt文件中提取这些数组后,我想将它传递给另一个包含js函数(比如f)的“index.html”文件,该函数将参数作为三个数组。现在,我如何将提取的数组x,y,z从main.go传递到index.html中的函数f – chinmay 2011-06-14 08:07:25