Javascript 很难从AJAX响应中剥离HTML标记
我有一个非常简单的web应用程序,我遇到了一些问题。我有两个文件 helloWorld.jsp:Javascript 很难从AJAX响应中剥离HTML标记,javascript,jquery,html,ajax,jsp,Javascript,Jquery,Html,Ajax,Jsp,我有一个非常简单的web应用程序,我遇到了一些问题。我有两个文件 helloWorld.jsp: int result = 0; out.println("<html><body>"+result+"</body></html>"); <html><head> <script type="text/javascript> function getHelloWorld() { $
int result = 0;
out.println("<html><body>"+result+"</body></html>");
<html><head>
<script type="text/javascript>
function getHelloWorld() {
$.get("/helloWorld.jsp, function(data) {
var temp = $.trim(data);
temp = temp.text(); //have also tried temp.html() and a few other things
$('#status').val(temp);
});
}
window.onload = function() {
getHelloWorld();
};
</script></head>
<body><div id='status'></div></body></html>
int结果=0;
out.println(“+result+”);
getHelloWorld.jsp:
int result = 0;
out.println("<html><body>"+result+"</body></html>");
<html><head>
<script type="text/javascript>
function getHelloWorld() {
$.get("/helloWorld.jsp, function(data) {
var temp = $.trim(data);
temp = temp.text(); //have also tried temp.html() and a few other things
$('#status').val(temp);
});
}
window.onload = function() {
getHelloWorld();
};
</script></head>
<body><div id='status'></div></body></html>
获取HTML并将其放入jQuery对象(这将导致jQuery将其放入文档片段并解析HTML),然后从jQuery对象提取文本:
function getHelloWorld() {
$.get("/helloWorld.jsp", function(data) {
var temp = $(data).text();
$('#status').val(temp);
});
}
window.onload = getHelloWorld;
工作演示:
有人可能想知道,如果您只需要一个数字,为什么要从服务器返回HTML。也许您应该返回JSON,这只是一个数字,然后jQuery将为您处理JSON响应,并给出您想要的数字。如果您使用JSP,最好以这种方式包含JSP页面(在服务器端):
但如果要使用JQuery,请尝试以下方法:
$.get("/helloWorld.jsp", function(data)
{
document.getElementById("status").innerHTML = data;
});
$('#status').load("helloWorld.jsp");
当您包括上面的类似内容时,它会剥离html和主体标记。退一步,看看更大的图景:一旦您得到ajax响应,它就只是一个字符串。来自ajax并不意味着它很特别。您应该询问如何在java中从字符串中剥离html。请注意,首先要弄清楚如何避免将信息嵌入html可能要容易得多。JSP作为JSON构建模板系统实际上非常有用。它不关心它是否生成HTML。在这里我返回0只是因为这是一个简单的例子,我试图在移动到更复杂的版本之前开始工作。这个答案很有帮助,谢谢。