javascript - (HTML) JavaScript + PHP - $_GET 错误

标签 javascript php html get

想要实现的目标:

  • 索引页面 (index.html),允许用户注册,该页面在 JavaScript (index.js) 上运行以检查字段 (代码段 index.js 中未提及),然后重定向到注册页面 (scripts/register.php),然后将值添加到数据库。

实际发生的情况:

  • 它正确重定向到 PHP 页面,但是使用 $_GET 方法时似乎没有传输任何值:我得到一个空页面。

我做错了什么?

代码:

<小时/>

index.html(仅一个片段)

<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
<script type = "text/javascript", src = "index.js">
</script>
<小时/>

index.js(仅一个片段)

document.getElementById("signup").onclick = signup;
var aref = "refcode";
function signup()
{
    window.location.href = 'scripts/register.php?emailaddress=' + document.getElementById("email").value + '&username=' + document.getElementById("user").value + '&password=' + document.getElementById("pass").value + '&aref=' + aref;
}
<小时/>

scripts/register.php(仅一个片段)

<?php 
echo $_GET['emailaddress'];
echo $_GET['username']; 
echo $_GET['password']; 
echo $_GET['aref'];
?>

编辑:我不小心复制了“scripts/register.php”的错误代码,对所有为我纠正它的答案表示抱歉

最佳答案

您从不提交表单(因为您似乎没有表单),因此除了嵌入到 URL 中的数据之外,您什么也得不到(这是非常不安全的,发送敏感数据(例如类似的密码)。

但是,我不确定你为什么要把事情复杂化。

如果您想使用 GET,无需自己构建 URL,只需使用 GET 方法设置表单并使用常规提交发送即可,不需要 javascript。使用隐藏字段作为 aref 值(您可以在生成表单时、提交之前等填充它,无论什么对您有用):

<form method="GET" action="scripts/register.php">
    <input name="aref" type="hidden" value="refcode" />
    <input name="user" type="text" id="user" size="25" />
    <input name="email" type="text" id="email" size="25" />
    <input name="pass" type="password" id="pass" size="25" />
    <input type="submit" name="signup" id="signup" value="Sign Up" />
</form>

同样,将方法更改为 POST 将是一个更好的主意。当然,然后你需要访问像$_POST['aref']等变量。就像这样:

<form method="POST" action="scripts/register.php">
    <input name="aref" type="hidden" value="refcode" />
    <input name="user" type="text" id="user" size="25" />
    <input name="email" type="text" id="email" size="25" />
    <input name="pass" type="password" id="pass" size="25" />
    <input type="submit" name="signup" id="signup" value="Sign Up" />
</form>

以及 PHP(用于 POST):

<?php 
echo $_POST['email'];
echo $_POST['user']; 
echo $_POST['pass']; 
echo $_POST['aref'];
?>

关于javascript - (HTML) JavaScript + PHP - $_GET 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19642499/

相关文章:

javascript - 打开弹出窗口并在用户单击弹出窗口外的任何位置时将其隐藏

javascript - 为什么我不能对这个元素应用任何东西?

php - MySQL 5.5.32 上的连接问题

javascript - JavaScript 中的数字比较

php - 更新数据库中的外键以在 PHP 中注册用户日志

php - 我如何获取数据库中字段名(名称)中的所有数据并将其存储在变量数组中?在 PHP 和 MYSQL 中

javascript - 关闭浏览器窗口/选项卡时如何删除 localStorage 项目?

javascript - 将 wordpress 中的样式表和脚本与 functions.php 链接起来

javascript - JSON 为空的 Chart.js

javascript - 获取 select 中键的名称