【问题标题】:Use buttons to post to a php script使用按钮发布到 php 脚本
【发布时间】:2013-12-16 05:16:18
【问题描述】:

基本上,我将为我正在处理的应用程序创建一个控制面板,它只是一组按钮。我想将有关按下哪个按钮的信息传递给将处理实际命令的脚本。我不太清楚如何使用 POST 来做到这一点......这是我目前拥有的一些代码。

<php
include("writemessage.php");
echo " <form action='writemessage.php' method='POST'>
<input type='submit' name='message' value='custom1'/>
<input type='submit' name='message' value='custom2'/>
</form>";
?>

就我通过阅读一些教程和文档收集到的信息而言,它应该可以工作吗? writemessage.php 脚本只是将信息放在一个文件中,我用 GET 对其进行了测试,它工作得很好。

<?php
$file = 'log.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Change file to command.
$current = $_POST[message];
// Write the contents back to the file
file_put_contents($file, $current);
?>

我希望它在后台提交。我希望它看起来好像没有刷新或在任何地方导航..

【问题讨论】:

  • 如果你这样做会发生什么 var_dump($_POST);在您的接收脚本中?作为一个好习惯,也值得关闭你的文件。
  • 您可以为每个按钮制作一个单独的表单,这可能有助于清除问题。
  • 您希望在每次单击按钮时提交页面吗?还是你想让它在后台提交数据?
  • @RobertSeddon-Smith file_put_contents 和 file_get_contents 都会自动关闭文件。
  • 我希望它在后台提交。我希望它看起来好像不会刷新或在任何地方导航..

标签: javascript php button


【解决方案1】:

没有 Ajax

事实上它是有效的……只是需要修复一些细节(在 cmets 中注明):

<?php //<-- here it was "<php" fix that!
    include("writemessage.php");
    //Don't sent people over to writemessage, otherwise why did you include it?
    echo '<form action="" method="POST">
    <input type="submit" name="message" value="custom1"/>
    <input type="submit" name="message" value="custom2"/>
    </form>';
    //Note: I changed quotes, no big deal
    echo $current; //you can read $current
?>

writemessage.php:

<?php
    $file = 'log.txt';
    if (isset($_POST['message'])) //check if isset, also use quotes
    {
        // Change file to command.
        $current = $_POST['message']; //again quotes
        // Write the contents back to the file
        file_put_contents($file, $current);
    }
    else
    {
        if (file_exists($file)) //check if file exists
        {
            // Open the file to get existing content
            $current = file_get_contents($file);
        }
        else
        {
            // default value?
            //$current = '???';
        }
    }
?>

阿贾克斯

我没有注意到您说“在后台提交”,这是否意味着您不想加载页面?你可以用 Ajax 做到这一点......

<?php include("writemessage.php"); ?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
    function _submit(value)
    {
        //This is the value set locally, do you want to be able to get values from other users? that is a whole level more complex
        $('#current').html(value);
        //Here we send the info the server via AJAX with jQuery
        var ajax = $.ajax(
        {
            type: "POST",
            url: "writemessage.php",
            data: {message: value}
        });
        //This is the value form the server, note: it may change from another client and this will not be updated
        ajax.done(function(response)
        {
            $('#current').html(response);
        });
    }
</script>
<form action="">
    <input type="button" name="message" value="custom1" onclick="_submit('custom1')"/>
    <input type="button" name="message" value="custom2" onclick="_submit('custom2')"/>
</form>
<span id="current"><?php echo $current; ?></span>

注意 1:我使用 jQuery 从 url http://code.jquery.com/jquery-1.10.2.min.js 选择您想要的版本并将其放置在您的服务器中。

writemessage.php:

<?php
    $file = 'log.txt';
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && array_key_exists('message', $_POST))
    {
        $current = $_POST['message'];
        file_put_contents($file, $current);
        echo $current; //this is the response we send to the client
    }
    else
    {
        if (file_exists($file)) //check if file exists
        {
            $current = file_get_contents($file);
        }
        else
        {
            //$current = '???';
        }
    }
?>

注意2:你也对POST-REDIRECT-GET感兴趣。

【讨论】:

  • 使用严格相等检查可能是个好主意:$_SERVER['REQUEST_METHOD'] === 'POST'。 +1
  • @jgetrost 必须是拼写错误,请参阅条件 array_key_exists('message', $_POST) 必须与 $current = $_POST['message']; 匹配。
  • @Theraot,我忘了用你的替换我的 writemessage,一切都更好,效果很好。非常感谢。
【解决方案2】:

确保您的按钮具有不同的名称,这就是您要在 $_POST 数组中引用它们的方式。

例如,试试这个:

<input type='submit' name='message_1' value='custom1'/>
<input type='submit' name='message_2' value='custom2'/>

【讨论】:

    【解决方案3】:

    1 - 由于您想通过后台提交,您需要使用 Ajax。我将展示如何使用 Jquery 的 Ajax。

    2- 因为你想在后台发帖,你不再需要&lt;form&gt;

        <php
        include("writemessage.php");
        ?>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
    
            //Post data to "writemessage.php" on background (AJAX)
            function customSubmit(optionVal)
            {
    
                $.ajax({
                  url: "writemessage.php",
                  data: { 
                        'message': optionVal
                    },
                }).done(function(data) {
                  //if you want to see what this return, use alert(data);
                });
    
            }
    
    
        </script>
    
    
    
    echo "
    <input type='button' name='message1' value='custom1' onclick="javascript:customSubmit("custom1");"/>
    <input type='button' name='message2' value='custom2' onclick="javascript:customSubmit("custom2");"/>
    ";
    ?>
    

    3 - 现在在您的读取文件中,您可以读取 POST "hidOption" 作为所选按钮的值:

    <?php
    $file = 'log.txt';
    // Open the file to get existing content
    $current = file_get_contents($file);
    
    // Change file to command.
    $current = $_POST["message"]; //Here is "hidOption"!
    
    // Write the contents back to the file
    file_put_contents($file, $current);
    ?>
    

    就这么简单。

    【讨论】:

      【解决方案4】:
      <form method="post">
          <div class="response"></div>
          <input type="submit" name="message" value="custom1" />
          <input type="submit" name="message" value="custom1" />
      <form>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script>
          jQuery(function ($) {
              $('form').on('submit', function (e) {
                  e.preventDefault();
                  $.ajax({
                      context : this,
                      data : $(this).serialize(),
                      type : 'post',
                      url: 'writemessage.php'
                  }).success(function (response) {
                      $(this).find('.response').html(response);
                  });
              });
          });
      </script>
      

      另外,你的 writemessage.php 文件可以清理一下。

      <?php
      $file = 'log.txt';
      if (file_exists($file))
      {
          // Do some kind of validation on your input.
          if (in_array($_POST['message'], array('custom1', 'custom2'))
          {
              file_put_contents($file, $_POST['message']);
              echo "<p>The value is {$_POST['message']}</p>";
          }
          else
          {
              echo '<p class="error">Illegal value!!</p>';
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-14
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多