dongxili9934 2011-06-14 07:00
浏览 248
已采纳

通过go将数组传递给外部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.

  • 写回答

2条回答 默认 最新

  • doufen2769 2011-06-15 18:04
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败