【问题标题】:PHP $_POST Undefined index Error "Username"PHP $_POST 未定义索引错误“用户名”
【发布时间】:2018-12-15 19:26:39
【问题描述】:

我想在 POST 中使用 php 脚本从我的 html 表单中获取一些数据,但是这个脚本是在 javascript 脚本中调用的,当我尝试获取数据时出现以下错误:“未定义索引”

谁能帮帮我?对不起,我刚刚开始学习 PHP

部分 HTML:

<form class="form" id="myform" method="post">
<div class="form__group">
  <input type="text" placeholder="Username" id="Username" name="Username" class="form__input" />
</div>
</form>

部分JS脚本:

if (errors == false) {
    var Username = document.getElementById("Username");
    var Password = document.getElementById("Password");
    $.ajax({
        url: "scripts/register.php",
        success: function () {
            alert('Success');
        }
    });

部分 PHP 脚本:

$Username = $_POST['Username'];
$Password = $_POST['Password'];

【问题讨论】:

  • 建议您先阅读 $.ajax 文档以设置datamethod
  • 什么是确切的错误,无法注意到表单中的密码字段。
  • @charlietfl 抱歉,我听不懂……我该怎么办?
  • 您没有指定要发送哪些数据,或者应该通过什么方法发送。
  • 您必须将数据发送给$_POST才能读取,并且您需要将方法设置为POST。也建议学习一些ajax/php教程

标签: javascript php ajax post indexing


【解决方案1】:

你最好先阅读文档http://api.jquery.com/jquery.ajax/

var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
    method: 'POST',
    url: "scripts/register.php",
    data: {
        Username: Username,
        Password: Password
    },
    success: function() {
        alert('Success');
    }
});

【讨论】:

  • 如果他使用jquery,建议jquery值选择器:Username: $("#Username").val() , Password: $("#Password").val()
  • @IncredibleHat:是的,你是对的。我的代码中有时会出现那种“混合风格”,非常混乱;)
  • 很容易做到,尤其是在从旧代码迁移到 jquery 时。我花了一个月的时间清理一个网站。不好玩。所以我尝试建议“如果你明白了,就去完整的 jquery”=]
  • 我实际上建议这样做:data: $('#myform').serialize() 而不是手动获取每个输入。这样,您可以在 HTML 中添加输入,jQuery 会自动选择它。
  • @IncredibleHat 我怎样才能发送整个表单,然后获取其中的数据? (例如发送表单并获取它包含的
猜你喜欢
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 2016-08-17
  • 1970-01-01
  • 2017-07-21
相关资源
最近更新 更多