传递变量PHP,Javascript location.reload和HTML输入

时间:2015-02-08 16:42:18

标签: javascript php html post reload

我有一个页面,通过点击按钮运行MySQL查询。查询结果显示大约6个左右的列,大约有100行。

我希望用户能够根据列标题求助查询结果。几乎只是使用相同的查询将它们发送到同一页面。只是求助。

所以这就是我到目前为止,所有这些都在同一个剧本中。

HTML表格(以PHP回显)

echo "<th id='frame_data_table'><a onClick='innerChange()' href='#'>Command</a></th>";


Javascript功能

function innerChange() {
    document.getElementById("innerTest").value = "Changed it.";
    location.reload(true);
}

HTML输入标记和php表单处理

<?php echo "-->" . $_POST['commandSort'] . "<--"; ?>
<form method="post">
    <input type="text" id="innerTest" name="commandSort" value="command" />
</form>

当我执行此操作时,当页面重新加载时,echo $_POST['commandSort']显示任何内容。原始值和更改的值都不会显示。

真的,我需要的只是$_POST['commandSort']来获取更改的输入框的值,然后我可以实现将我想要的任何值放入我的查询中以便按照我想要的顺序进行排序。

提前致谢!

- 安东尼

=============================================== ===================

更新:解决方案

对此的解决方案(功劳归于我选择作为答案的用户之一)是使用document.getElementById['mainForm'].submit()。这就是我所拥有的。

HTML表格

<html>
<!--...some html code here...-->
<form method="post" id="mainForm" action="example.com/results.php">
  <!--...more code inside of the form here...-->
  <input type="checkbox" name="command" value="command" id="command"/><p>Command</p>
  <!--...more code inside of the form here...-->
  <input type="hidden" name="hiddenSort" id="hiddenSort" />
  <!--...more code inside of the form here...-->
</form>
<!--...some more html code here...-->
</html>

PHP example.com/results.php使用Javascript的页面

<?php
/*...more php code here...*/
<if (isset($_POST['command'])) {
  ?><th id="frame_data_table"><a href="javascript:sortFunction('command');">Command</a></th><?php
}
/*...more php code that displays the query result (while(...)) here...*/
?>

Javascript功能

<script>
  function sortFunction(x) {
    var sortVar = x;
    document.getElementById("hiddenSort").value = x;
    document.getElementById("mainForm").submit();
  }
</script>

说明:在获取并显示初始查询结果后,如果用户单击“命令”列链接,document.getElementById['mainform'].submit()将重新提交与先前运行相同的表单,同时传递变量通过javascript函数x。变量决定了如何使用查询,因为所有真正需要完成的工作都是在PHP中填充"ORDER BY " . $_POST['commandSort']的变量。如果您遇到类似的问题,请随时给我发消息,以便进一步解释。

感谢所有回复的人。

- 安东尼

3 个答案:

答案 0 :(得分:2)

$_POST['commandSort']为空,因为您没有提交表单,请尝试代替

location.reload(true);

document.forms["form1"].submit();

重命名

<form method="post" id="form1">

答案 1 :(得分:1)

您确定要为此使用JavaScript吗?它可以用HTML和PHP完成。

例如

<tr>
<th><a href="myfile.php?sort=blah1">Header Text 1</a></th>
<th><a href="myfile.php?sort=blah2">Header Text 2</a></th>
..
</tr>

然后在PHP中,您可以使用以下命令检索该值:

$sort = $_GET['sort'];

答案 2 :(得分:0)

点击按钮即可:

window.location.href = window.location.href.replace( /[\?#].*|$/, "?q=mysort" );

并将排序选项设为$sort= $_GET['q'];