douqufan9148 2018-09-08 01:09
浏览 146
已采纳

将Go函数传递给html / js按钮“ onclick”响应

I am using Go's "net/http" package to pass data between the html and the backend in Go. For example, we can used the location of an image like this:

<img src={{.MyPicture}} width=200 height=auto/>

We can do the same thing to pass in functions to the html and call them:

{{if .MyBool}}
    {{.MyFunction}}
{{end}}

Now my question is: how do I set the response of a button to call my function? I would expect this to work, but it doesn't:

<button onclick={{.ShowMoreLinks}}>Show more!</button>

I get "[js] Declaration or statement expected." I've tried wrapping it in a script (both inline and in the header), but neither of these seem to work. JS can't handle the passed in variable.

  • 写回答

1条回答 默认 最新

  • doubushi0031 2018-09-08 02:00
    关注

    Actually, you're using Go's template mechanism to prepare the HTML that you send to the browser. This only fills in placeholders and ultimately only produces a string (in this case HTML) that will be sent over the network to the browser for interpretation. It's the browser that can only handle interactivity with the user via events such as "onclick". Furthermore, these events have to be Javascript code, like a JS expression or a function call:

    onclick="jsFunction()"
    

    You could make your Go template provide the function to be called in the placeholder:

    onclick="{{.JSFuncCall}}"
    

    Here ".JSFuncCall" would have to evaluate to some JS function name (and the parentheses to make the call) that you must have defined in your JS client-side code. That Javascript function could then make an XHR call to the server at some specific URL that triggers a Go handler, runs the Go code you want to run, and then returns a response that you can then handle back in the JS function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器