简体   繁体   中英

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. And it show the data from my post in not in json format. How can I change my code to post the data in json format?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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