简体   繁体   English

如何在PHP echo中调用javascript函数/编写脚本

[英]How to call javascript function/write script inside PHP echo

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未定义,如何解决此错误

document.myForm is undefined when you are calling the script because it is being run before the form element has been received by the browser. 调用脚本时document.myForm是未定义的,因为它是在浏览器收到form元素之前运行的。 You need to put the script after the form tag, or use a document.onload event handler (or similar). 您需要将脚本放在form标签之后,或使用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自动立即提交表单的原因超出了我。)

If that's literally your code, then it's got syntax errors up the wazoo. 如果从字面上看这是您的代码,那么wazoo就会出现语法错误。

Try: 尝试:

<?php if (isset($_POST['submit_details'])) { ?>
   <script type="text/javascript">submitForm();</script>
<?php } ?>

Try moving the script to the bottom of the page, or better, listen to the window.onload event. 尝试将脚本移动到页面底部,或者更好的方法是监听window.onload事件。 When the script is loaded by the browser, the DOM hasn't finished loading and cannot find document.myForm yet. 当浏览器加载脚本时,DOM尚未完成加载,因此无法找到document.myForm。

Why dont you just put the javascript submit inside the input like so? 您为什么不将javascript提交像这样输入呢?

<input type="submit" name="submitdetails" onclick="javascript:submitform();" />

Then use $post with jquery to run the page. 然后使用$ post和jquery来运行页面。

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

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