【问题标题】:Why do I need to press the submit button 2 times before the javascript function work?为什么我需要在 javascript 功能工作之前按 2 次提交按钮?
【发布时间】:2015-01-09 23:16:41
【问题描述】:

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

      <!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>

【问题讨论】:

  • 你知道PHP无论如何都会先运行吧?您是否也知道它第一次运行时 my_var 完全不包含任何内容?您需要的是一个 ajax 调用,您可以将数据输入并将数据写入新文件。
  • 尝试将 $(document).ready(function(){your js} 放在你的 js 中
  • @Rhillz 没有使用 jQuery。这将导致范围问题和 $ 未定义这一事实引发错误
  • @Royalty 我不知道。如何使用 ajax 提供数据以将其写入新文件?
  • $Rhillz 我尝试放置 $(document).ready(function(){my js} 但即使单击 2 次也无法使用。

标签: javascript php codeigniter


【解决方案1】:

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

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

但是要跟进 cmets。您的脚本实际上是偶然发生的。如果您想写入文件,请使用表单上的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>

AJAX

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);
 ?> 

【讨论】:

  • 我是否需要包含此代码 如果我不打算使用 AJAX 方法?还是此代码仅适用于 AJAX 方法?
  • @JustinFrancisToral 在任何一种情况下,您都需要将该 php 移动到单独的文件中。然后从 post 操作或 ajax 调用该文件。
【解决方案2】:

您需要将数据发送给控制器。 你也可以发送到任何 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);

【讨论】:

  • 第一个 Ajax (vanilla) 示例不会按照 OP 的预期方式工作。 OP 希望将表单内的表发送到服务器并将其存储在 php 文件中。 html 被存储到隐藏的输入中并发布到服务器。您需要将此作为变量添加到发送函数中。
  • 我迷路了。上面的所有代码都在 标记内吗?我需要更改我的 html 代码吗?
【解决方案3】:

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

【讨论】:

  • 是的,这是解决问题的最简单方法。但是,我建议再次阅读其他答案和 cmets。他们就如何稳健地实现您想要的功能提供了可靠的建议。
  • 我遇到了一个新问题。如何在 javascript 中访问控制器功能?
猜你喜欢
  • 1970-01-01
  • 2015-10-27
  • 2019-05-30
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
相关资源
最近更新 更多