【发布时间】:2016-04-19 20:43:05
【问题描述】:
我已经到处找了好几个小时,但找不到适合我的解决方案。我有一个简单的 html 表单,它获取 3 个表单输入,并且需要将数据发送到 Web 服务的 @POST 方法。创建后,Web 服务将显示更新后的列表。谁能告诉我我做错了什么?
投票.html
<script>
function myFunction()
{
data = $(this).serialize();
$.ajax({
url: 'http://localhost:8080/places3/resourcesC/create',
method: 'POST',
dataType: 'text',
data: data,
success: function() { alert("Worked"); },
error: function(error) { alert("Error"); }
});
}
</script>
</head>
<body>
<form onsubmit="myFunction()">
<p>City: <input type="text" name="city" /> </p>
<p>POI1: <input type="text" name="poi1" /> </p>
<p>POI2: <input type="text" name="poi2" /> </p>
<input type="submit" value="Submit" />
</form>
网络服务的@POST方法
@POST
@Produces({MediaType.TEXT_PLAIN})
@Path("/create")
public Response create(@FormParam("city") String city,
@FormParam("poi1") String poi1,
@FormParam("poi2") String poi2) {
checkContext();
String msg = null;
// Require both properties to create.
if (city == null || poi1 == null || poi2 == null) {
msg = "Property 'city' or 'poi1' or 'poi2' is missing.\n";
return Response.status(Response.Status.BAD_REQUEST).
entity(msg).
type(MediaType.TEXT_PLAIN).
build();
}
// Otherwise, create the Place and add it to the collection.
int id = addPlace(city, poi1, poi2);
msg = "Place " + id + " created: (city = " + city + " poi1 = " + poi1 + " poi2 = " + poi2 + ").\n";
return Response.ok(msg, "text/plain").build();
}
【问题讨论】:
-
目前发生了什么?成功或错误功能是否触发?控制台有错误吗?
-
它不应该警告错误。它应该在 Ajax 请求解决之前提交表单。
-
它警告“错误”并且什么都不做,但 url 确实得到了字符串
-
localhost:8080/ajax/?city=flint&poi1=UofM&poi2=MottCC
-
尝试从错误中获取更好的信息。类似
error: function(jqXHR, textStatus, errorThrown){console.log('jqXHR.status: " + jqHR.status); console.log('textStatus: " + textStatus); console.log('errorThrown: " + errorThrown); }