【发布时间】:2017-05-01 04:55:37
【问题描述】:
我的 jsp 页面包含一组食物,其中有 4 项。
当用户在数组中存在的文本框中输入食物名称时,我会得到一个包含 4 个字符串的输出,说明是否找到它。
根据数组中食物的位置,我会在相应的字符串中得到实际答案。如果输入的食物是数组中的第 4 个元素,那么 AJAX 写入的第 4 个字符串给出正确答案。
我的截图显示了问题
如果输入的值为 Samosa Pav,则显示输出,第二个字符串给出正确的输出。
如果输入的值为misalPav,则显示输出,第四个字符串给出正确的输出
我需要进行哪些更改以确保从 AJAX 调用中只收到一个正确的输出?
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.jsp?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Chuff Bucket</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
%--
Document : index
Created on : 15 Dec, 2016, 7:07:55 PM
Author : KRISHNAJI
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String food = request.getParameter("food");
String foodArray[] = {"Vada Pav", "Samosa Pav", "Pav Bhaji", "Misal Pav"};
for(int i = 0; i < foodArray.length; i++)
{
if(food.equalsIgnoreCase(foodArray[i]))
{
out.println("Hey we do have " + food);
}
else if (food == "")
{
out.println("Enter a food");
}
else
{
out.println("We don't have " + food);
}
}
%>
</body>
</html>
[1]: https://i.stack.imgur.com/sBHnZ.jpg
[2]: https://i.stack.imgur.com/Xv7fG.jpg
【问题讨论】:
-
也许您可以尝试在打印后放置中断语句。外观遍历整个数组,所有 4 个项目,并为每个项目打印一次。
-
感谢道格拉斯,在 if elseif 和 else 中的 print 语句后使用 break 只会在文本框为空白或我输入数组中的第一项时给我正确的输出。请编辑 .jsp 文件。
标签: javascript html ajax jsp