简体   繁体   English

在表单中打印JS变量

[英]Print JS Variable in Form

I´d like to pass a javascript variable to php and I thought of using a hidden input field in my form. 我想将一个javascript变量传递给php,我想到了在表单中使用隐藏的输入字段。 Here is my code for that so far: 到目前为止,这是我的代码:

<input type="hidden" name="city" value="<script type='text/javascript'>document.write(geoip_city());</script>" />

Unfortunally this doesnt work as the output is exact the same as above instead of the cityname as value. 不幸的是,这不起作用,因为输出与上面的值完全相同,而不是城市名作为值。 Could any1 point me in the right direction? 有人能指出我正确的方向吗? I am not sure where the problem is.. 我不确定问题出在哪里。

Thanks! 谢谢!

Hidden variable was good idea (if it is part of a form that gets submitted). 隐藏变量是个好主意(如果它是要提交的表单的一部分)。

You can set it like this, provided that you add an id of city to this input. 如果您向此输入添加city ID,则可以这样设置。

<script type="text/javascript">
    document.getElementById('city').setAttribute('value', geoip_city());
</script>

You can put that script towards the bottom of the page, or with other javascript if you have some already. 您可以将该脚本放到页面底部,如果有的话,也可以放到其他JavaScript上。 just make sure that input element exists at the time that it runs 只要确保输入元素在运行时就存在

<script>
   function davidIsPedantic(){
      document.getElementById('city').value = geoip_city();
   }
</script>

<input type="hidden" id="city" name="city" />

Edit: There you go. 编辑:你去了。 Call the davidIsPedantic() function when you want to update the input, so long as the element has loaded. 要更新输入时,只要元素已加载,就调用davidIsPedantic()函数。 To call it as soon as the page is loaded, use this: 要在页面加载后立即调用它,请使用以下命令:

window.onload = davidIsPedantic();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM