javascript - 我的 AJAX post 变量无法访问我的 PHP

标签 javascript php ajax json

我做了一个AJAX函数,它确实有效,但我无法用PHP获取变量。这是我的代码:

// Validate signup
function validateSignup(){
    // Get values
    var username = document.getElementById("pm_username").value;
    var email = document.getElementById("pm_email").value;
    var password = document.getElementById("pm_password").value;
    // Make new object
    var data = {};
    // Make array from object
    data['data'] = [];

    // If values are not empty...
    if(username !== "" || email !== "" || password !== ""){
        data['data'].push(email, username, password);
        // Convert data to JSON string and make new XMLHttpRequest
        var json = JSON.stringify(data['data']), xhr = new XMLHttpRequest();

        // Page to open
        xhr.open("POST", "ajax/signup.php", true);
        // Set header to POST
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // Send values
        xhr.send(json);
        console.log(json);

        xhr.onload = function(){
            console.log(xhr.responseText);
        }

    }else{ // ...or throw new exception
        throw("Some thing was not filled in!");
    }
}

它有效,但我不知道如何在 PHP 中获取 JSON 变量。这是我的 PHP 代码(简单):

<?php

$json = $_POST['json'];
echo $json;
echo "Test";

?>

它有效,因为“测试”回显正在控制台中显示。但是,我得到了这个:

<br />
<b>Notice</b>:  Undefined index: json in <b>G:\usbwebserver\root\pokemonisle\ajax\signup.php</b> on line <b>3</b><br />
Test 

这意味着 $_POST['JSON'] 未被识别。我没有使用 jQuery,因为我想了解 XMLHttpRequests 的工作原理。

最佳答案

您没有发送名为“json”的发布数据,因此您无法在服务器端获取它。

尝试将您的数据对象字符串化

var json = "json="+JSON.stringify(data['data']);

并将其获取为

$json = $_POST['json'];

您可以查看此链接。 Send POST data using XMLHttpRequest

关于javascript - 我的 AJAX post 变量无法访问我的 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24323716/

相关文章:

javascript - Meteor 如何访问服务器端和客户端的 Facebook Graph Api

php - 我想合并sql数据库的两个函数?

javascript - 免费托管网站如何运作?

javascript - 如何使用 Ajax 成功在新选项卡中打开 URL?

javascript - 用箭头键改变图像?

javascript - 如何更改html header 的值

javascript - 如何在具有某些 ui View 的状态下管理工厂单个请求数据

php - 无法从 $this->db->last_query(); 得到结果;代码点火器

ajax - 没有页面刷新,Rails 3 ajax 更新部分不起作用

ajax - 有没有办法像jsf.ajax.addOnEvent一样获取Primefaces ajaxStatus中的请求数据