java - json ajax问题

标签 java javascript ajax json jsp

很抱歉问这个问题,但我已经为此工作了几个小时,我无法自己解决。

我必须在项目的一部分中使用 json,我能够让它工作,但现在它没有将它返回到正确的 jsp,而是只显示 json jsp。我很确定这是我接收 json 的方式。

这里是正在发生的事情的屏幕截图:

这是我需要使用 ajax 的 jsp,我想使用 ajax 填充第二个下拉列表:

the jsp I want to use ajax on

这是正在发生的事情,(这是正确的数据):

enter image description here

这是代码(对不起,它很长):

-我正在做ajax的jsp

    <script type="text/javascript">

/**
 * Utility function to create the Ajax request object in a cross-browser way.
 * The cool thing about this function is you can send the parameters in a two-dimensional
 * array.  It also lets you send the name of the function to call when the response
 * comes back.
 *
 * This is a generalized function you can copy directly into your code. *
 */
function doAjax(responseFunc, url, parameters) {
  // create the AJAX object
  var xmlHttp = undefined;
  if (window.ActiveXObject){
    try {
      xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
    } catch (othermicrosoft){
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {}
    }
  }
  if (xmlHttp == undefined && window.XMLHttpRequest) {
    // If IE7+, Mozilla, Safari, etc: Use native object
    xmlHttp = new XMLHttpRequest();
  }
  if (xmlHttp != undefined) {
    // open the connections
    xmlHttp.open("POST", url, true);
    // callback handler
    xmlHttp.onreadystatechange = function() {
      // test if the response is finished coming down
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        // create a JS object out of the response text
            var obj = eval("(" + xmlHttp.responseText + ")");
        // call the response function
        responseFunc(obj);
      }
    }

    // create the parameter string
    // iterate the parameters array
    var parameterString = "";
    for (var i = 0; i < parameters.length; i++) {
      parameterString += (i > 0 ? "&" : "") + parameters[i][0] + "=" + encodeURI(parameters[i][1]);
    }

    // set the necessary request headers
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", parameterString.length);
    xmlHttp.setRequestHeader("Connection", "close");

    // send the parameters
    xmlHttp.send(parameterString);
  }
}//doAjax

/**
 * Submits the guess to the server.  This is the event code, very much
 * like an actionPerformed in Java.
 */
function getSeats() {
  // this is how you get a reference to any part of the page
  var packInput = document.getElementById("pack");
  var pack = packInput.value;
//  while (packInput.childNodes.length > 0) { // clear it out
//    aSeats.removeChild(aSeats.childNodes[0]);
//  }

  // an example of how to do an alert (use these for debugging)
  // I've just got this here so that we know the event was triggered
  //alert("You guessed " + seat);

  // send to the server (this is relative to our current page)
  // THIS IS THE EXAMPLE OF HOW TO CALL AJAX
  doAjax(receiveAnswer, "ttp.actions.Sale3PackAction.action",
    [["pack", pack]]);

  // change the history div color, just 'cause we can
//  var randhex = (Math.round(0xFFFFFF * Math.random()).toString(16) + "000000").replace(/([a-f0-9]{6}).+/, "#$1").toUpperCase();
//  document.getElementById("history").style.background = randhex;
}

/**
 * Receives the response from the server.  Our doAjax() function above
 * turns the response text into a Javascript object, which it sends as the
 * single parameter to this method.
 */
    function receiveAnswer(response) {
  // show the response pack.  For this one, I'll use the innerHTML property,
  // which simply replaces all HTML under a tag.  This is the lazy way to do
  // it, and I personally don't use it.  But it's really popular and you are
  // welcome to use it.  Just know your shame if you do it...
  var messageDiv = document.getElementById("aSeats");
  messageDiv.innerHTML = response.aSeats;

  // replace our history by modifying the dom -- this is the right way
  // for simplicity, I'm just erasing the list and then repopulating it
  var aSeats = document.getElementById("aSeats");
  while (aSeats.childNodes.length > 0) { // clear it out
    aSeats.removeChild(aSeats.childNodes[0]);
  }
  for (var i = 0; i < response.history.length; i++) { // add the items back in
    var option = aSeats.appendChild(document.createElement("option"));
    option.appendChild(document.createTextNode(response.history[i]));
  }

  // reset the input box
  //document.getElementById("pack").value = "";

}
</script>


<% Venue v = (Venue)session.getAttribute("currentVenue"); %>
<% List<Conceptual_Package> cpList = Conceptual_PackageDAO.getInstance().getByVenue(v.getId()); %>

What Packages do you want to see?

 <form method="post" action="ttp.actions.Sale3PackAction.action">
 <select name="packid" id="pack">
     <% for (Conceptual_Package cp: cpList) { %>
    <option value="<%=cp.getId()%>"><%=cp.getName1()%></option>
    <% } %>


 </select>

    <input type="submit" value="  next  " onclick="getSeats();"/>

    </form>


<!--new-->


Available Seats:

 <select name="eventSeatid" id="aSeats">

    <option value="aSeats"></option>

 </select>


    <input type="button" value="  Add  "/>


Selected Seats:
 <form method="post" action="ttp.actions.sale4Action.action">
     <select name="eventSeat2id" size="10" id="seat2">


     <option value="seat2"></option>




 </select>

    </form>



<jsp:include page="/footer.jsp"/>

-json jsp

<%@page contentType="text/plain" pageEncoding="UTF-8"%>
<jsp:directive.page import="java.util.*"/>
{
  "history": [
<% for (String newSeats: (List<String>)session.getAttribute("newSeats")) { %>
      "<%=newSeats%>",
<% } %>
   ]
}

- Action 类

public class Sale3PackAction implements Action{
    public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        String packid = request.getParameter("packid");
        System.out.println("packid is: " + packid);
        Conceptual_Package cp = Conceptual_PackageDAO.getInstance().read(packid);
        request.setAttribute("cp", cp);
        List<Physical_Package> ppList = Physical_PackageDAO.getInstance().getByConceptual_Package(cp.getId());
        request.setAttribute("currentPack", ppList);
        session.setAttribute("aSeats", null);




        //return "sale3Pack_ajax.jsp";

        //new

        //HttpSession session = request.getSession();


        // ensure we have a history


       for (Physical_Package pPack: ppList){


        try {
            if (session.getAttribute("aSeats") == null) {
                LinkedList aSeatsList = new LinkedList<String>();
                session.setAttribute("aSeats", aSeatsList);

                    aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());

                session.setAttribute("newSeats", aSeatsList);

            } else {
                LinkedList aSeatsList = (LinkedList) session.getAttribute("aSeats");

                    aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());

                session.setAttribute("newSeats", aSeatsList);
            }

        } catch (DataException ex) {
            Logger.getLogger(Sale3PackAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        }


        // next jsp page to go to
        return "AjaxPack_json.jsp";

    }
}

最佳答案

呵呵,我想我们都处在你的位置上。花几个小时在某件事上最终意识到我们忽略了一些简单的细节。

阅读评论了解更多信息...

关于java - json ajax问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5534779/

相关文章:

java - freemarker - 字符串比较 - 不允许使用运算符

java - 行为和忙碌指示器

javascript - ajax调用后如何刷新数据表

java - 使用ajax和servlet上传文件

java - Spring-boot - 每个级别的日志文件的应用程序属性配置

java - JDBC 中的用户界面 - 查看表

javascript - 在 AngularJS 中显示 AJAX 加载栏

javascript - img src变化时给图片添加Slidein转场效果?

使用prototype属性的javascript继承

javascript - keyup 13 事件重复隐含提交 - 输入问题时提交表单