【发布时间】:2016-01-13 22:26:30
【问题描述】:
我必须与 JSP、AJAX 和 Java 聊天,但我遇到了一个问题:当我尝试使用我的变量来存储输入文本的值时,该变量为空。 如果我将 'action' 属性添加到表单中,变量 'textParam' 将具有输入文本的值,但是,如果我这样做,我必须通过操作重定向到页面,而我不这样做。
我需要在 JSP 页面中处理更大的内容,然后在 HTML 页面(这是一个 JSP 页面)中重新加载(重新加载部分不在实际探测中)。
当我按下按钮时,如何使用输入文本值填充“textParam”?
PS:我需要使用纯 javascript,而不是某些库:)
需要处理的JSP是:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
我的表格是这样的:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
.js 文件是这样的:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
【问题讨论】:
-
好吧,您的代码似乎正在获取文本,因为 document.getElementById('chatMessage').value 必须包含您想要的文本。您的问题不是关于 getChatText() javascript 函数吗?
-
是的,我想从 document.getElementById('chatMessage').value 中获取文本并在另一个页面中创建一个 Java 变量
-
我明白了。您是否尝试将服务器端的对话存储在两个页面的共同上下文中?您的解决方案可以使用 Servlet 吗?
-
我尝试了一些东西,但我不是很尝试。如果没有任何解决方案,我将接受 servlet。
-
非常感谢,我会去那里学习的。暂时我发现了问题: String textParam = request.getParameter("message");我在想'chatMessage'是参数,但它是'messages'
标签: javascript java html jsp request