2017-03-04 101 views
0

我有这个代码做http post,这个职位正在工作,但服务器端期望数据在json格式。它显示我的帖子中的数据不是以json格式。如何更改我的代码以json格式发布数据?jquery json http post - 如何将发布数据转换为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

要发布所有你需要做的就是指定在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>

+0

我试试你的代码,这是行不通的。 – CK8

+0

@ CK8有什么问题呢? –

+0

@ CK8我用一个工作端点更新了代码 –