为什么我需要在 javascript 函数工作之前按提交按钮 2 次


Why do I need to press the submit button 2 times before the javascript function work?

这是我的代码(我使用codeigniter作为我的框架,这是视图)。单击提交按钮后.php此代码应将名为 包含的内容的div 写入名为 newfile 的文件。但是我需要在将数据写入新文件之前单击按钮 2 次.php。请帮忙。我不知道我的代码出了什么问题。

      <!DOCTYPE html>
         <html lang="en">
           <head>
             <meta charset="utf-8">
             <title>Online Lodging Locator</title>
          </head>
        <script>
             function test(){
           var x = document.getElementById('contain').innerHTML;
            alert(document.my_form.my_var.value=x);
        <?php
          $content = $_POST["my_var"];
          $myfile = fopen("newfile.php", "w") or die("Unable to open file!");
          fwrite($myfile, $content);
          fclose($myfile);
           ?> 
           }
            </script>   
         <body>
           <form name="my_form" method="post">
            <input type="hidden" name="my_var">
            <div id="contain">
            <h1>Online Lodging Locator</h1>

            <table cellspacing="0" cellpadding="1" border="1">
         <tr>
            <td>COL 1 - ROW 1222<br />COLSPAN 3</td>
            <td>COL 2 - ROW 1</td>
            <td>COL 3 - ROW 1</td>
         </tr>
         <tr>
          <td rowspan="2">COL 2 - ROW 2 - COLSPAN 2<br /></td>
          <td>COL 3 - ROW 2</td>
         </tr>
         <tr>
          <td>COL 3 - ROW 3</td>
         </tr>
         </table>
          </div>
         <button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="test()">WRITE</button>
           </form>
         </body>
         </html>

解释为什么需要单击两次按钮:

@Royalty是正确的。php 首先运行。php 在您的脚本块中。它返回一个错误,因为$_POST['my_var'] undefined 。这是在脚本块中echoed的,导致您的页面由于error而暂停脚本。当您单击 submit .表单已提交(实际上是重新加载页面),并且这次填写了帖子 var。因此,PHP 中的错误意味着没有任何东西被回显到脚本块中,这意味着浏览器不会引发任何错误。现在单击提交执行函数test

但要跟进评论。您的脚本实际上是偶然工作的。如果要写入文件,请使用窗体上的 action 属性或执行ajax调用。

表单操作

<form name="my_form" action="file.php" method="post">
   <input type="hidden" name="my_var">
   <button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="test()">WRITE</button>
</form>
<script>
   function test(e)
   {
       e.preventDefault();
       document.my_form.my_var.value = document.getElementById('contain').innerHTML;
       document.getElementsByName("my_form")[0].submit(); //submit the form.
   }
</script>

阿贾克斯

function sendAjax(e) {
    e.preventDefault(); //prevent the default action of the form.
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               //request is complete and loaded
               //do something with the response.
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }
    xmlhttp.open("POST", "file.php", true); //true means asynchronously.
    xmlhttp.send("content="+document.getElementById('contain').innerHTML);
}

.HTML

    <button type="submit" class="btn btn-default" name="SEARCH" id="SEARCH" onclick="sendAjax()">WRITE</button>

file.php应替换为服务器上运行的 php 文件:

 <?php
      $content = $_POST["my_var"];
      $myfile = fopen("newfile.php", "w") or die("Unable to open file!");
      fwrite($myfile, $content);
      fclose($myfile);
 ?> 

您需要将数据发送到控制器。你也可以发送到任何php文件,但你已经有了CodeIgniter。

.JS

var base_url = '<?=base_url()?>';
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()  {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)  {
        document.getElementById('contain').innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("POST", base_url+"path/to/controller",true);
    xmlhttp.send();

使用 jQuery,您可以更轻松地控制数据类型:

var content = $('#contain').html();
var base_url = '<?=base_url()?>';
$.ajax({
  type: "POST",
  contentType: 'html',
  url: base_url+"path/to/controller", //"path/to/file.php"
  data: content
});

.PHP

$myfile = fopen("newfile.php", "w") or die("Unable to open file!");
if(isset($_POST['data'] {
    $content = $_POST['data'];
} else {
    $content = 'No data';
}
echo $content;
fwrite($myfile, $content);
fclose($myfile);

我解决了。我只需要将 if(isset($_POST['my_var'] {)){} 添加到我的 php 代码中。我不需要单击提交按钮两次。