簡體   English   中英

jQuery json http post-如何將發布數據轉換為json格式?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM