我做了一个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/