我一直在尝试在我的 javaee 应用程序中运行 jquery 而不是普通的 javascript。下面的代码显示了我无法理解的应用程序。每次我运行该应用程序时,它都会给我一个空白页面。不知何故 jquery 没有加载到 tomcat 服务器上。我该怎么做?
<html>
<head>
<title>Erycoking | JSON</title>
<script src="WEB-INF/lib/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON("${pageContext.request.contextPath}/getCDs.jsp", function (response) {
var cds = response.catalog.cd;
alert(JSON.stringify(cds));
$.each(cds, function (ind, val) {
$('body.container').append('<li>' + cds[ind].title + ' : '
+ cds[ind].artist + '</li>');
});
});
});
</script>
</head>
<body>
<ul class='container'></ul>
</body>
</html>
我的 getCDs.jsp 在这里
<jsp:useBean id="fetchBean" class="fetcher.FetchXML" />
<jsp:getProperty name="fetchBean" property="json" />
我的 FetchXML.java 在这里
public class FetchXML {
public void setJson(String json){}
public String getJson(){
JSONObject json = null;
try {
String xml = "";
URL url = new URL("http://www.w3schools.com/xml/cd_catalog.xml");
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line = br.readLine()) != null) xml+= line;
br.close();
xml = xml.replace("'", "");
json = XML.toJSONObject(xml.toLowerCase());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
}
最后是我的 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>fetch.jsp</welcome-file>
</welcome-file-list>
</web-app>
这是我的文件结构 enter image description here
最佳答案
举个例子:
正如您在图片中看到的,我在 WEB-INF
的同一级别上有 index.html
和 script.js
文件文件夹。
然后如果需要访问我的 index.html 文件中的 javascript 资源我只需要使用相对路径,在这个例子中两个资源都位于我的 web 应用程序的根路径
Web 应用程序网址为:-> http://localhost:8080/myapp
然后索引页面是: -> http://localhost:8080/myapp/index.html
然后是 script.js 文件 -> http://localhost:8080/myapp/script.js
查看您的 html 文件,我认为一种可能的解决方案是这样的,只有当 jquery-3.2.1.min.js
资源与 处于同一级别时,它才会起作用WEB-INF
文件夹:
<html>
<head>
<title>Erycoking | JSON</title>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON("${pageContext.request.contextPath}/getCDs.jsp", function (response) {
var cds = response.catalog.cd;
alert(JSON.stringify(cds));
$.each(cds, function (ind, val) {
$('body.container').append('<li>' + cds[ind].title + ' : '
+ cds[ind].artist + '</li>');
});
});
});
</script>
</head>
<body>
<ul class='container'></ul>
</body>
</html>
关于java - JQuery 在 tomcat 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45969909/