我必须使用 JSP、AJAX 和 Java 进行聊天,但遇到一个问题:当我尝试使用变量来存储输入文本的值时,该变量为 null。 如果我将“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;
}
最佳答案
问题出在这里:
String textParam = request.getParameter("chatMessage");
我试图获取“chatMessage”参数,它只是输入的名称。解决方法是获取在 js 中定义和请求的“message”参数:
String textParam = request.getParameter("message");
关于javascript - JSP 聊天 - 如何将 HTML 中的值解析为 JSP 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34778260/