javascript检查$_POST是否存在

标签 javascript php jquery html post

我有这样的场景:

  • 在我的index.html中,有一个带有文本框的表单和一个带有POST方法的按钮,并操作另一个名为middlescan.html的页面
  • middlescan.html 在 body onload 事件中调用名为 checkpost 的 js 函数
  • middlescan.html 中的 js 函数必须检查 $_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.js文件中

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

    ?>
    

但响应始终为“nullo” 怎么了?

提前致谢

最佳答案

您必须在 php 中进行检查或对某些 php 脚本使用 ajax 调用,因为除了通过 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;
  }
?>

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

关于javascript检查$_POST是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21466733/

相关文章:

javascript - 克隆 SVGMatrix 的规范方法是什么?

javascript - 跨浏览器 "inArray"函数(没有 jQuery)

php - 页面加载后,获取每个项目的 youtube View

javascript - jQuery Ajax - 仍在重新加载页面 - Laravel 分页

php - 将当前屏幕截图并通过php保存为png图片

javascript - 如何更改复选框选择行的背景颜色

javascript - Python Flask + Angular 错误 : 'StoreController Undefined'

javascript - 如何使用 GitHub api 查找存储库的 'm' 最旧的分支

php - paypal商户SDK安装方法

php - 在php中对数组应用分页