我对 Ajax 还很陌生。从 HTML 中的不同下拉列表中选择一个值后,我使用 Ajax 来填充下拉列表。问题是,我得到了所需的输出以及 HTML 格式。
JavaScript 代码是 -
function showHint(str)
{
// alert("Ajax - " + str);
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","AjaxCall.jsp?q="+str,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("xmlhttp.responseText - " + xmlhttp.responseText );
}
}
}
在 xmlhttp.responseText(警报)中,我得到输出 -
我只需要输出 -
D1&&&D2&&&D3&&&D4
我不需要这个额外的 HTML 代码。
我的 AjaxCall.jsp 是 -
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="com.Search.Struts2.AccessCheckComponent"%>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setContentType("text/plain");
%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
System.out.println("-------------------jsp -------------- " );
String cpmt = request.getParameter("q");
System.out.println("cpmt -!!Ajax - jsp !! " + cpmt);
String deckStr = AccessCheckComponent.CheckCompartmentDeckRelationship(cpmt);
System.out.println("deckList -!!Ajax - jsp !! " + deckStr);
response.getWriter().write(deckStr.toString());
%>
</body>
</html>
最佳答案
您获得了 HTML,因为 JSP 在响应中将其发送回来。要解决这个问题,您需要设置 contentType
页面到text/plain
并从 JSP 中删除所有 HTML 元素(即 <!DOCTYPE...>
、 <html>
以及所有内容。只需将 D1&&&D2&&&D3&&&D4
写入输出即可。
更简洁的解决方案是编写一个简单的 Servlet
。这样,您就可以避免所有 JSP 开销。
关于javascript - 如何仅获取纯文本(字符串)来响应 Ajax url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28742388/