如何解决通过go将数组传递给外部js
| 我有一个.txt文件,其中包含(x,y,z)形式的3d点。 使用go,我将点坐标提取到数组X [],Y [],Z []中。 现在,我需要将这些数组传递给外部javascript(即 js中的功能)。 我该怎么做呢? 通常,如何将一些参数传递给.html中的任何js函数 文件。解决方法
假设您正在运行的服务器是Go程序,则应该采用其他方法。
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.
}
});
}
在Go方面:
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服务器就不必在运行时执行转换。
, 我会说:只需通过(通过引用)即可:
function doSomethingWithPpoints(x,y,z){
//do something with for example x[0],y[1] etc.
}
//later on
doSomethingWithPoints(points1,points2,points3);
[编辑]这可能是一个主意:对数组进行序列化以对作为URL的查询字符串的附件进行字符串处理:
var url = \'http://somesite.net/somefile.html\'+
\'?points1=1,2,3&points2=3,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个属性(点1-3)的对象pointsObj
//pointsObj looks like this
{ points1: [1,3],points2: [3,1],points3: [5,7] }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。