[英]jquery json http post - How to convert the post data to json format?
我有这段代码在做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>
要发布所有您需要做的就是在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.