【发布时间】:2015-08-29 20:22:16
【问题描述】:
这是我正在尝试做的事情(现在已经有一天多了:(用户单击书名的链接,我阅读了该书的名称。然后我使用该书名并发出 Ajax 请求泽西资源。在该泽西资源中,我调用 POJO 类中的一个方法,其中一个方法与数据库交互并将数据发送回泽西资源。我有很多错误,但我已经能够修复它们一次。我目前遇到的错误是:
您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在“?”附近使用的正确语法在第 1 行
这是我的 JavaScript 代码:
function dealWithData(nameOfBook){
var bookName = encodeURI(nameOfBook);
console.log("http://localhost:8080/library/rest/books/allBooks/"+bookName);
var requestData = {
"contentType": "application/json",
"dataType": "text",
"type": "GET",
"url": "http://localhost:8080/library/rest/books/allBooks/"+bookName
**//beforeSend has been added as an edit to original code**
beforeSend: function (jqXHR, settings) {
var theUrlBeingSent = settings.url;
alert(theUrlBeingSent);
}
};
var request = $.ajax(requestData);
request.success(function(data) {
alert("Success!!");
});
request.fail(function(jqXHR, status, errorMessage) {
if((errorMessage = $.trim(errorMessage)) === "") {
alert("An unspecified error occurred. Check the server error log for details.");
}
else {
alert("An error occurred: " + errorMessage);
}
});
}
出于某种原因,在上面的代码中,console.log 行显示带有空格的 url 被编码为 %20,而在变量 'requestData' 中,url 没有该编码。我无法理解为什么。
这是我的资源的代码:
@GET
@Path("/allBooks/{bookName}")
@Produces(MediaType.APPLICATION_JSON)
public Response getBook(@PathParam("bookName") String bookName){
System.out.println("Book name is: "+ bookName);
BookInformation bookInfo = new BookInformation();
String bookInformation =bookInfo.bookInformation(bookName);
ResponseBuilder responseBuilder = Response.status(Status.OK);
responseBuilder.entity(bookInformation);
Response response = responseBuilder.build();
return response;
}
这里是 bookInformation 方法:
public String bookInformation(String bookName){
String infoQuery = "Select * from bookinfo where name = ?";
ResultSet result = null;
conn = newConnection.dbConnection();
try
{
preparedStatement = conn.prepareStatement(infoQuery);
preparedStatement.setString(1, bookName);
result = preparedStatement.executeQuery(infoQuery);
}
catch (SQLException e)
{
e.printStackTrace();
}
try
{
if(result != null){
while(result.next()){
availability = result.getString("availability");
isbn = result.getInt("isbn");
hardback = result.getString("hardback");
paperback = result.getString("paperback");
name = result.getString("name");
}
}
else{
System.out.println("No result set obtained");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
//I will build this String using a String builder which I will return
String finalBookInformation = information.toString();
return finalBookInformation;
}
早些时候,在 dataType 中,我有 json,它抛出了一个不同的错误,但我意识到我没有构建 json,所以我将 dataType 更改为 text 并且该错误消失了。我的参数化查询没有执行。如果我尝试对数据库中的值进行硬编码,它可以正常工作,但当我使用准备好的语句时就不行了。我最终想返回 JSON,但现在我只想让它工作。任何帮助将不胜感激。我已经尝试过研究并尽我所能,但它不起作用。是导致问题的编码吗?是我的 Ajax 调用吗?任何帮助表示赞赏。谢谢。
【问题讨论】:
标签: java javascript mysql ajax json