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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度