日期:2014-05-16  浏览次数:20708 次

新手练习ajax的时候碰到这样的问题

XML code
function change(v1){
              var xmlhttp = getXmlHttpRequest();
              xmlhttp.open('post','city.do',true);
              xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
              xmlhttp.onreadystatechange=function(){
                  if(xmlhttp.readyState == 4){
                      var txt = xmlhttp.responseText;
                      var arr = txt.split(';');
                      $('s2').innerHTML = '';
                      for(i=0;i<arr.length;i++){
                          var arr1 = arr[i];
                          var arr2 = arr1.split(',');
                          var op = new Option(arr2[1],arr2[0]);
                          $('s2').options[i] = op;
                      }
                  }
              };
              xmlhttp.send('name = ' +v1);
          }
      </script>
  </head>
  
  <body style="font-size:30px;">
      <select id="s1" style="width:120px;" onchange="change(this.value);">
          <option value="hn">湖南</option>
          <option value="bj">北京</option>
      </select>
      <select id="s2" style="width:120px;"></select>
  </body>

这是jsp页面的内容

Java code

public class Action extends HttpServlet{
    public void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,IOException{
        String uri = request.getRequestURI();
        String path = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(path.equals("/city")){
            String name = request.getParameter("name");
            if(name.equals("hn")){
                out.println("yy,岳阳;hh,怀化;cs,长沙");
            }else if(name.equals("bj")){
                out.println("cy,朝阳;hd,海淀;dc,东城;xc,西城");
            }
        }
        out.close();
    }
}


这是java里面的action,然后就配置了web.xml
XML code
<welcome-file-list>
    <welcome-file>city.jsp</welcome-file>
  </welcome-file-list>
  
   <servlet>
      <servlet-name>Action</servlet-name>
      <servlet-class>web.Action</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>Action</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>

这是我看着别人给的例子配置的,目的是当我选择北京的时候,可以出来北京的那几个地名,选择湖南的时候可以出现湖南的那几个地名,可就是抛出空指针异常,

------解决方案--------------------
java.lang.NullPointerException
at web.Action.service(Action.java:20)
20行应该是 :
 String name = request.getParameter("name"); 
 if(name.equals("hn")){
这里吧

改这里试试

xmlhttp.send('name = ' +v1);

去掉空格:
xmlhttp.send('name=' +v1);
------解决方案--------------------
if(null!=path&&path.equals("/city")){
String name = request.getParameter("name");
if(null!=name&&name.equals("hn")){