【发布时间】:2018-02-28 01:04:18
【问题描述】:
嘿,我有一个 ajax 请求,当我按下按钮时会调用它,但是 servlet 映射不起作用。当我按下按钮时,它不会进入控制器。 这是向控制器发出 ajax 请求的脚本。
<script type="text/javascript">
function getData() {
var dataToBeSent = {
uName : $("#jsonResponse").text() //
};
$.ajax({
url : 'something/testing', // Your Servlet mapping or JSP(not suggested)
data : dataToBeSent,
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
};
</script>
#jsonResponse 是一个
是首先动态分配的。 这是控制器:
@Controller
@RequestMapping("/something")
public class Test {
@RequestMapping("/testing")
public void test(@RequestBody String yey){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/api?user=root&password=1234");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String query = "INSERT INTO test(Id, nume) value (default, ?)";
PreparedStatement preparedStmt;
try {
preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, yey);
preparedStmt.execute();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(yey);
}
}
【问题讨论】:
-
你有 404 错误吗?到达服务器?是不是js控制台报错了?
-
@MohamedBathaoui 是的,我有这个错误 POST localhost:8080/ApiAi/something/testing 404 ()
标签: javascript java ajax spring-mvc controller