javascript - 未设置 PHP GET 变量

标签 javascript php jquery ajax html

我有一个显示表单的 registraion php 类,当单击注册按钮时,调用登录 javascript 文件中的函数。此文件使用 ajax 将数据发布到 index.php 文件。我的 index.php 文件无法访问此数据,尽管发布成功(调用警报时 ajax 成功为真)。

Login.js

var loginData, urlPath;

// Allow users to log in or register
function Login() {

    loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val();
    urlPath = "../index.php?action=register";

    // Send the login/registration data to database
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: urlPath,
            data: loginData,
            success: function (result) {
                alert("success");
            }
        })
    })
}

index.php

<?php 

    require_once("Model/model.php");
    require_once("Controller/controller.php");
    require_once("View/view.php");

    $model = new Model();
    $view = new View();
    $controller = new Controller($model, $view);

    $controller->Begin();

    // Client wants to register
    if(isset($_GET['action'])) {
        if($_GET['action'] == "register") {
            echo '<script type="text/javascript">alert("hello")</script>';
        }
    }
?>

最佳答案

您使用了 ajax 的 POST 方法。所以也像下面这样以 POST 方式发送数据:-

// Send the login/registration data to database
$(document).ready(function() {
    var username = $("#usernameField").val();
    var email = $("#emailField").val();
    var password = $("#passwordField").val();
    $.ajax({
        type: "POST",
        url: "../index.php",
        data: {"username":username,"email":email,"password":password,"action":"register"},
        success: function (result) { 
            alert(result);//check the change 
        }
    });
});

然后在 php 端将 GET 更改为 POST:-

<?php 

    require_once("Model/model.php");
    require_once("Controller/controller.php");
    require_once("View/view.php");

    $model = new Model();
    $view = new View();
    $controller = new Controller($model, $view);

    $controller->Begin();

    // Client wants to register
    //single condition can do the job and use POST instead of GET
    if(isset($_POST['action']) && $_POST['action'] == "register" ) { 
      echo "hello"; //check the change
    }
?>

注意:- 请也注意注释。(添加到代码中)

关于javascript - 未设置 PHP GET 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466219/

相关文章:

javascript - ScriptResource.axd 的 View 状态无效?

javascript - bizcharts y 轴标签覆盖

php - 当我在内部使用 _GET 时,MySql 数据库查询不起作用

javascript - 为什么我的网络应用程序在打开时无法重新加载

javascript - 浏览器关闭时推送通知不起作用

php - 如何在php mysql中离线更新用户状态

php - 将 phpdbg 与内置 php 服务器一起使用?

javascript - 如何在鼠标悬停时更改 div 背景图像?

python - web2py:检测下拉小部件的变化

javascript - 如何在页面准备好之前通过 javascript 加载外部字体