如何在 PHP echo 中调用 javascript 函数/编写脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7744343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call javascript function/write script inside PHP echo
提问by n92
I have written piece of code, below is the code
我写了一段代码,下面是代码
<script type="text/javascript">
function submitform()
{
document.myform.action='http://mysite/index.php';
document.myform.submit();
}
</script>
<?php
if(isset($_POST['submit_details']))
{
echo "<script typ=javascript> submitform();</script>";
}
?>
<form id="myform">
------
------
<input type="submit" name="submit_details">
</form>
when i try to submit the form , it gives me error document.myform is undefined, how to solve this error
当我尝试提交表单时,它给我错误 document.myform is undefined,如何解决这个错误
回答by daiscog
document.myForm
is undefined when you are calling the script because it is being run beforethe form element has been received by the browser. You need to put the script after the form tag, or use a document.onload
event handler (or similar).
document.myForm
调用脚本时未定义,因为它在浏览器接收到表单元素之前运行。您需要将脚本放在表单标签之后,或者使用document.onload
事件处理程序(或类似的)。
(Although quite why you want to automatically and immediately submit a form by JS without your user doing anything is beyond me.)
(虽然你想在没有你的用户做任何事情的情况下通过 JS 自动并立即提交表单的原因超出了我的理解。)
回答by Marc B
If that's literally your code, then it's got syntax errors up the wazoo.
如果这确实是您的代码,那么它就会出现语法错误。
Try:
尝试:
<?php if (isset($_POST['submit_details'])) { ?>
<script type="text/javascript">submitForm();</script>
<?php } ?>
回答by beefyhalo
Try moving the script to the bottom of the page, or better, listen to the window.onload event. When the script is loaded by the browser, the DOM hasn't finished loading and cannot find document.myForm yet.
尝试将脚本移动到页面底部,或者更好地监听 window.onload 事件。当浏览器加载脚本时,DOM 还没有加载完成,还没有找到 document.myForm。
回答by Juan Gonzales
Why dont you just put the javascript submit inside the input like so?
你为什么不像这样把 javascript submit 放在输入中?
<input type="submit" name="submitdetails" onclick="javascript:submitform();" />
Then use $post with jquery to run the page.
然后使用 $post 和 jquery 来运行页面。