通过AJAX发送JSON到PHP失败
问题描述:
我想通过ajax发送JSON字符串到PHP文件。问题是,我张贴在变,当我使用jQuery的AJAX方法不被传递如下图所示:通过AJAX发送JSON到PHP失败
<DOCTYPE html>
<html>
<head>
<title>Assignment 4</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-4"></div>
<div class="col-sm-4">
<form action="json.php" method="POST">
<div class="form-group">
<label for="email">Username:</label>
<input type="text" class="form-control" id="userid" name="userid">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pwd">
</div>
<button type="submit" class="btn btn-default" id='btn' onclick="JSONstring()">Submit</button>
</form>
</div>
<div class="col-sm-4"></div>
<script>
function JSONstring() {
obj = {
username: "",
password: "",
}
obj.username = document.getElementById('userid').value;
obj.password = document.getElementById('pwd').value;
console.log(obj.username + ", " + obj.password);
var jsonObj = JSON.stringify(obj);
$.ajax({
type: 'POST',
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});
}
</script>
</body>
</html>
奇怪的是,当我尝试和AJAX的老式方法,我能得到我所期待的RAW POST数据:
var jsonObj = JSON.stringify(obj);
request = new XMLHttpRequest();
request.open("POST", "json.php", true);
request.setRequestHeader("Content-type", "application/json");
request.send(obj);
我的PHP文件只是试图让变量和转储:
<?php
$directions = json_decode($_POST['json']);
var_dump($directions);
?>
可有人请点我在正确的方向?
答
dataType仅意味着您期望得到JSON响应。
请尝试使用contentType代替。
$.ajax({
type: 'POST',
contentType: "application/json",
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});
+0
以内的其他变量中感谢,这有很大的帮助。我也没有返回JSON,而是将其作为返回类型。 –
[接收JSON POST用PHP(http://stackoverflow.com/questions/18866571/receive-json-post-with-php) – Schlaus
尝试删除的可能的复制 - >'数据类型:“JSON ''你发送的不是json,而是使用json发送的请求。 – Ahmad
我认为JQuery自动将对象转换为字符串。所以你不应该需要JSON.stringify(obj)。同时检查json.php中的$ _POST变量的值。你的json字符串可能会在$ _POST –