[英]AJAX with JSON and PHP not returning any data… I think
为什么我的代码不起作用?
我知道我要发送数据,
但是没有回应。
$(document).ready(function(){
$("form").submit(function () {
var uname = document.getElementById("username").value;
var pword = document.getElementById("password").value;
var postData = {
username: uname,
password: pword
};
var PostDataString = JSON.stringify(postData);
alert(PostDataString);
$.ajax({
url: "test.php",
type: "GET",
data: PostDataString,
dataType: 'json',
contentType: 'json',
cache: false,
success: function (ReturnData) {
alert("Yay!");
}
});
});
});
$json = $_GET["PostDataString"];
$jsonarray = json_decode($json, true);
echo $jsonarray;
json_decode
用于将JSON字符串转换为PHP构造。 json_encode
正好相反,就是你想要的。 您期望JavaScript端有json数据类型; 如果jQuery在这种情况下没有获得有效的JSON,则会抛出错误。
JSON.stringify
转换是不必要的,因为$.ajax
接受其data
属性的JavaScript对象。 实际上,对JSON进行字符串化会阻止它作为任何参数发送。
如果删除JSON.stringify
发送postData
。 您可以访问$_GET['username']
和$_GET['password']
,但不能访问其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.