使用JSP

时间:2015-07-14 06:55:11

标签: javascript ajax jsp

我正在尝试使用ajax获取动态输出,例如“如果有人添加食物名称然后ajax在后台运行并动态地给我输出是否可以在阵列中提供食物和放弃相应的消息”。但是我没有得到..请参考下图:

Html File ::

'<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Foodstore</title>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3> The FoodStore</h3>
Enter the food you want :
<input type="text" id="userInput"/>
<div id="underInput" />
</body>
</html>`

Java script ::

`/**
* 
*/

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){

try{

     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
    catch (e) {
        // TODO: handle exception
         xmlHttp = false;
    }
}

else{
try{

     xmlHttp = new XMLHttpRequest;
    }
    catch (e) {
        // TODO: handle exception
         xmlHttp = false;
    }
}

if(!xmlHttp)
    alert("Sorry cannot creat object");
else
    return xmlHttp;
}

function process(){

if(xmlHttp.readyState==0 || xmlHttp.readyState==4){

    var food=encodeURIComponent(document.getElementById("userInput").value);

    xmlHttp.onreadystatechange= handleServerResponse;
    xmlHttp.open("GET","foodstore.jsp?food=" +food,true);
    xmlHttp.send(null);
}else{

    setTimeout('process()', 1000);
}
}

function handleServerResponse(){

if(xmlHttp.readyState==4){
    if(xmlHttp.status=200){

        var xmlResponse = xmlHttp.responseXML;
        var xmlDocumentElement = xmlResponse.documentElement;
        var message = xmlDocumentElement.firstChild.data;

        document.getElementById("underInput").innerHTML = '<span           style="color:blue">' 
        + message + '</span>';
        setTimeout('process()', 1000);
    }else {
        alert('Something went wrong!');
    }
}
}`

JSP ::

`<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<%@ page contentType="text/xml" %>

<response>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<c:set var="flag" value="0"></c:set>
<c:set var="s" value="${param.food }"></c:set>
<c:set var="a" value="${fn:split('grapes,apple,banana', ',')}"       scope="application" />
<c:forEach var="i" begin="0" end="2">
<c:if test="${fn:contains(a[i],s) }">
<c:set var="flag" value="1"></c:set>
</c:if>
</c:forEach>

<c:if test="${flag eq 0 }">
<c:out value="Sorry We do not have  ${s} !!"></c:out>
</c:if>

<c:if test="${param.food eq null }">
<c:out value="Plese Enter Food name!!!"></c:out>
</c:if>

<c:if test="${flag eq 1 }">
<c:out value="Yes We Do have ${s} !"></c:out>
</c:if>

</response>    `

提前致谢:)

0 个答案:

没有答案