尝试从JavaScript接收参数时,我得到null。我已经发了几篇文章,但无法弄清楚我在代码中犯了哪些错误。
以下是我发送请求的代码:
function funcOnChange() {
var index = document.detail.Class.selectedIndex;
var valueSelected = document.detail.Class.options[index].value;
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
alert("Alert Dialog! Gaurav");
}
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/ReportFetcher/FormHandler', true);
xhr.send(valueSelected);
}
我从以下代码中获取valueselected
并且valueselected
是正确的:
<select name="Class" onchange="funcOnChange()">
<option value="None">None</option>
<option value="FIRST">FIRST</option>
<option value="SECOND">SECOND</option>
<option value="THIRD">THIRD</option>
<option value="FOURTH">FOURTH</option>
<option value="FIFTH">FIFTH</option>
<option value="SIXTH">SIXTH</option>
<option value="SEVENTH">SEVENTH</option>
<option value="EIGHTH">EIGHTH</option>
<option value="NINTH">NINTH</option>
<option value="TENTH">TENTH</option>
</select><br>
我收到了关于FormHandler.java的onPost()的回调
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
log.info("IN form doPost");
String selectedClass = request.getParameter("Class");
log.info(selectedClass);
}
问题:此处selectedClass
为空。
建议我犯错的地方。
答案 0 :(得分:1)
试试这个
function funcOnChange() {
var index = document.detail.Class.selectedIndex;
var valueSelected = "Class="+document.detail.Class.options[index].text;
.....
.....
xhr.send(valueSelected);
}
答案 1 :(得分:0)
如果您通过任何代理/ HTTP监控工具(我使用Charles)看到您的请求和响应,您将看到您没有将请求作为键值对发送(简单来说,您不发送Class = value)但是您只发送Class属性的值作为字符串。 (如果您在选择框中选择第三个选项,则为第三个)。如果要将服务器上的数据作为键值对读取,则需要发送FormData。
function funcOnChange() {
var index = document.detail.Class.selectedIndex;
var valueSelected = document.detail.Class.options[index].value;
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
alert("Alert Dialog! Gaurav");
}
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://fiddle.jshell.net/', true);
var form = new FormData();
form.append("Class",valueSelected)
xhr.send(form);
}