json ajax问题

发布于 2024-10-30 01:57:17 字数 8127 浏览 1 评论 0 原文

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

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

以下是正在发生的情况的屏幕截图:

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

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

在此处输入图像描述

这是代码(抱歉太长了):

-我正在执行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%>",
<% } %>
   ]
}

-操作类

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";

    }
}

I am sorry to ask this but i've been working on this for hours and I can't figure it out on my own.

I have to use json for part of a project and I was able to get it to work but now it's not returning it back to the right jsp but instead just displaying the json jsp. I am pretty sure it is how I am receiving the json.

here are screen shots of what is happening:

this is the jsp that I need to use ajax on, I am wanting to populate the second dropdown using ajax:

the jsp I want to use ajax on

this is what is happening instead, (it's the right data):

enter image description here

here is the code(sorry it's long):

-the jsp I am doing ajax on

    <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"/>

-the 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%>",
<% } %>
   ]
}

-the action class

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";

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠意 2024-11-06 01:57:17

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

阅读评论以获取更多信息...

Hehe, I think we've all been in your place. Spending hours on something just to eventually realize that we overlooked some simple detail.

Read comments for more information...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文