简体   繁体   English

jQuery json http post-如何将发布数据转换为json格式?

[英]jquery json http post - How to convert the post data to json format?

I have this code doing http post, the post is working but the server side expecting data in json format. 我有这段代码在做http发布,该发布正在工作,但是服务器端期望json格式的数据。 And it show the data from my post in not in json format. 而且它以json格式显示我发布的数据。 How can I change my code to post the data in json format? 如何更改代码以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>

To post all you need to do is specify the post in a data object like I've done below and specify the dataType: json . 要发布所有您需要做的就是在data对象中指定发布,就像我在下面所做的那样,并指定dataType: json (by the way you had a typo, you're missing a ) somewhere) (由你有一个错字的方式,你错过了)的地方)

 <!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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM