javascript检查$ _POST是否存在

时间:2014-01-30 20:24:00

标签: javascript php jquery html post

我有这种情况:

  • 在我的index.html中,一个带有文本框的表单和一个带有POST方法的按钮,另一个页面名为middlescan.html
  • middlescan.html在body onload事件中调用名为checkpost的js函数
  • js函数进入midlescan.html,必须检查$ _post变量是否设置或不是空白,在正面情况下做一些事情,否则返回index.html

我的问题是: 如何在javascript中检查是否有$ _POST调用?

我现在的情况:

  1. 在我的index.html中:

    <form id="form1" name="form1" method="post" action="middlescan.html">
    <p>
    <label for="oStxt"></label>
    </p>
    <table width="60%" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td width="6%">&nbsp;</td>
    <td width="17%"><input type="text" name="oStxt" id="oStxt" /></td>
    <td width="77%"><input type="submit" name="button" id="button" value="Invia" /></td>
    </tr>
    </table>
    </form>
    
  2. 在middlescan.html

    <body onload = ckpost()>
    
  3. 3.in js file

    function ckpost() {
    
    // only continue if we have a valid xmlHttp object
    if (xmlHttp)
    {
    // try to connect to the server
    try
    {
      // initiate reading the async.txt file from the serve
    
      xmlHttp.open(“POST", "php/check.php", true);
      xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
      // change cursor to "busy" hourglass icon
    
    
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
    }
    }
    
    1. 在我的checkpost.php

      <?php
      $datat = array();
      
      if(!is_null($_POST['oStxt']) || $_POST['oStxt'] != "") {
      

      $ datat [urlpost] = $ _POST ['oStxt'];

      } else {
      

      $ datat [urlpost] =“nullo”;

      } 
      

      // Creo il文件json echo json_encode($ datat);

      ?>
      
    2. 但反应永远是“nullo” 有什么问题?

      提前致谢

3 个答案:

答案 0 :(得分:2)

你必须在php中进行检查或使用一些ajax调用某些php脚本,因为除了通过ajax调用之外,javascript无法访问后端脚本语言。

如果你需要基于某些php变量

执行特定的js代码,你可以在php中执行以下操作
<?php
  if(isset($_POST['somevar']) && $_POST['somevar']=="Some Value") {
     echo <<<END
     <script>
        $(document).ready(function(){
           //do something here.
        });
     </script>
END;
  }
?>

或者已加载js文件

<?php
  if(isset($_POST['somevar']) && $_POST['somevar']=="Some Value") {
     echo <<<END
     <script type="text/javascript" src="/someJSFile.js"></script>
END;
  }
?>

但请注意,在浏览器加载页面并且未在php中执行之前,javascript将不会运行。

答案 1 :(得分:1)

$_POST是javascript无法访问的服务器端变量!

如果您想在发送前检查表单中的POST变量:

<form action="some_url" onSubmit="if (this.input_name.value == ''|| this.input_name.value==' ') { alert('empty value found'); return false;}">

如果要检测是否进行了Ajax调用:

 $(document).bind("ajaxSend", function(){
       alert('ajax was used!');
    });

答案 2 :(得分:0)

相反,你可以检查每个表单元素是否在客户端本身设置,如果它只是为了检查表单元素是否填充或为空。

像:

if(document.getElementById("form_element1")) {
     alert('Value set');
}

否则,你必须用PHP创建一个桥文件,这样你就可以通过AJAX调用该文件了。

相关问题