duanlei7101 2019-08-30 18:18
浏览 50
已采纳

将Javascript变量的值发送到Go变量中

I need to read the value of a Javascript variable (JS2GO) in my Go code (v.Hostname). I do not know how to do it.

I have read a bit about syscall/js but I could not find anything.

It is the Javascript code:

    $(document).on("keypress", "input", function(e){
      if(e.which == 13){
          var JS2GO = $(this).val();
      }
    });

And here is the form I have in my .gohtml file.

    <form method="POST">
      <input id="myInput" type="text" name="host">
      <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1">
    </form>

P.S.

I came up with this solution because I can't click on "submit" button (it is hidden), then it doesn't send the results to my Go code. It means that I cannot read the value of input by this code: v.Host = r.FormValue("host"). Please let me know if my approach is not optimal.

  • 写回答

1条回答 默认 最新

  • dongnai5905 2019-09-02 13:23
    关注

    Based on comment of @G.aziz, I have found a solution mentioned here. In my case, it got fixed in this way:

    <form method="POST">
        <input id="myInput" type="text" name="host" style="min-width: 220px;" placeholder="Hostname; e.g. crowe.org">
        <input id="submitBtn" type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1">
    </form>
    

    and the Ajax code:

    $(document).ready(function () { 
        $('#submitBtn').click(function () {
            $.ajax({
              url: '/',
              type: 'POST',
              dataType: 'HTML',
              data : {
                ajax_post_data: $('#myInput').val()
              },
            });
         });
    });
    

    Then in my Go file, I can get the value like this

    if r.Method == "POST" {
        v.Host = r.FormValue("ajax_post_data")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)