【发布时间】:2017-07-30 19:50:49
【问题描述】:
我的 jQuery AJAX 实现不能正常工作,所以如果我想添加、删除、更新产品或检索所有网站,它根本不会对我的点击做出反应。
当有人想要提交具有指定 ID 的表单时,所有表单字段都会分配给适当的变量。之后,根据表单字段变量生成一个新的 JSON 文档。然后执行 AJAX 调用。它指向在表单标签的 action 属性中指定的 URL。 JSON用作需要处理的数据。
You can downlaod my project from here
出现错误:
localhost:8080/api/sites Failed to load resource: net::ERR_CONNECTION_REFUSED
2localhost:8080/api/sites/ Failed to load resource: net::ERR_CONNECTION_REFUSED
来自我的 Java 类:
@RequestMapping(method = RequestMethod.GET, value = "/api/sites")
public List<Site> getAllSites(){
return siteService.getAllSites();
}
@RequestMapping(method = RequestMethod.POST, value = "/api/sites")
public void addSite(@RequestBody Site site){
siteService.addSite(site);
}
复制问题的网页:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<hr><p> New page </p>
<input name="search" type="text" maxlength="100" id="search"/>
<button onclick="getAllSites()"> Show All </button>
<hr>
<hr>
<p> Id: <input name="search" type="text" maxlength="100" id="id"/></p>
<p> First name: <input name="search" type="text" maxlength="100" id="name"/></p>
<button onclick="addSite()"> Save </button>
<div id="site"></div>
<script>
function addSite()
{ var data = {
id: document.getElementById("id").value,
name: document.getElementById("name").value
}
$.ajax({
url: "http://localhost:8080/api/sites",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "POST",
dataType: "json",
data: JSON.stringify(data)
});
}
function getAllSites()
{
$("#site").html("");
$.getJSON("http://localhost:8080/api/sites/", function(data)
{
for (var i in data) {
$('#site').append("<p>ID: " + data[i].id + "</p>")
$('#site').append("<p>Name: " + data[i].name + "</p>")
}
});
}
</script>
</body>
</html>
【问题讨论】:
-
很遗憾,“它不起作用”不足以让我们为您提供帮助。您能否在单击按钮发出 AJAX 请求后检查控制台并告诉我们您看到的错误(如果有)
-
@Mina 我怀疑您是否有类似这样的 url 映射:
http://localhost:8080/api/sites123。你确定这是你想要的吗? -
我的项目的想法是我有一个单独的网页,可以放在任何地方。它不包含在我的 java 项目中。
-
能否提供您在浏览器控制台中看到的脚本错误?
-
源代码中的@Mina 我看到你定义了以下映射:
value = "/api/sites/{id}"。但在 javascript 中,您在 id 之前缺少/符号。试试吧。另外,不要忘记使用@提及网站上的特定人员
标签: javascript java jquery ajax spring