我有这个代码做http帖子,帖子正在工作,但服务器端期望json格式的数据。它以非json格式显示我帖子中的数据。如何更改我的代码以json格式发布数据?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("http://www.example.com/post",
dataType: 'json',
{
"userID" :"JohnDoe",
"timeStamp" :""
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
console.log(val);
}
}
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
答案 0 :(得分:0)
要发布您需要做的所有事情,请在data
对象中指定帖子,例如我在下面完成并指定dataType: json
。 (顺便说一下,你有一个错字,你在某个地方遗漏了)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("button").click(function() {
$.post({
type: 'POST',
url: "https://jsonplaceholder.typicode.com/posts",
data: {
"userID": "JohnDoe",
"timeStamp": ""
},
dataType: 'json',
success: function(data, status) {
console.log(data);
alert("Data: " + data + "\nStatus: " + status);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
console.log(val);
}
}
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
</head>
<body>
<button>
Send an HTTP POST request to a page and get the result back
</button>
</body>
</html>
&#13;