通过AJAX将JSon对象发布到Webservice

时间:2018-01-18 14:10:31

标签: javascript java json ajax jersey

我试图通过AJAX将JSon格式的对象发送到我的Java后端,但是我没有成功。 我想知道语法是否正确。



<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scripts/jquery.min.js.download"></script>
 <script src="scripts/jquery.imagemapster.js.download"></script>
<script>

$(document).ready(function(){
    $("button").click(function(){
	var myJSon = {"name":"Jo","age":30,"city":"Ny"};
     
       $.ajax({
		type: "POST",
		url: 'http://localhost:8080/Servidor/server',
		//contentType: "application/json;charset=utf-8",
		dataType: "json",
		data: JSON.stringify(myJSon),
		success: function (data){
		   alert('Sucess');
	        },
		error: function () {
		   alert('Error');
	        }
       });
    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>
&#13;
&#13;
&#13;

如果未注明行contentType: "application/json;charset=utf-8",我会在后端收到以下错误:INFO: Could not find grammar element for class java.lang.String

语法是否正确?错误可能来自后端本身吗?

P.S。:对不起,我的英文不好

1 个答案:

答案 0 :(得分:0)

你的代码很好,你刚刚在AJAX调用上拼错了“成功”(你需要2个字母c而不是1个)。因此,将sucess: function(data){...}替换为success: function(data){...} https://jsfiddle.net/stephentillman/aow5pah2/