dtvpl739577 2014-06-20 09:09
浏览 52

我的AJAX post变量没有进入我的PHP

I have made an AJAX function, and it actually works, but I can't get the variable with PHP. This is my code:

// 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!");
    }
}

It works, but I don't know how I should get the JSON variable in my PHP. This is my PHP code (simple):

<?php

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

?>

It works, because the "Test" echo is being displayed in the console. However, I am getting this back:

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

That means that the $_POST['JSON'] is not being recognised. I am not using jQuery because I want to learn how XMLHttpRequests work.

  • 写回答

3条回答 默认 最新

  • douyi8315 2014-06-20 09:18
    关注

    Your POST array doesn't contain a field named json.

    Try the following:

    <?php 
    var_dump($_POST);
    ?>
    

    to check which fields you are getting.

    To prevent the error you could try:

    <?php
    if(isset($_POST['json']))
    {
        $json = $_POST['json'];
        echo $json;
    }
    ?>
    

    and similarly to get other variable you could use:

    <?php
    if(isset($_POST['username']))
    {
        $username = $_POST['username'];
        echo $username;
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条