如何使用servlet + ajax制作动态内容

时间:2013-12-06 04:50:50

标签: java jquery ajax jsp servlets

我正在尝试学习jsp + servlet,如果我基本完成它(jsp将数据发送到servlet然后servlet从db获取数据并设置属性并转发到新页面),一切进展顺利但是当我尝试时问题就出现了更新一些内容而不重新加载页面(使用ajax将数据发送到servlet并转发到jsp文件,我使用jquery加载特定的),它没有改变那些内容。

的Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        int id = Integer.parseInt(request.getParameter("id"));

        Database db = new Database();
        ProductTable productTable = new ProductTable(db);
        Product product = productTable.findByID(id);
        db.close();

        request.setAttribute("productDetail", product);
        request.getRequestDispatcher("/view/backend/selectProduct.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

JSP模态

<!-- language: html -->
<div class="modal fade" id="modalEditProduct" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                <div class="tableSelectProduct">
                    <%@include file="selectProduct.jsp" %>
                </div>
            </div>
            <div class="modal-footer">
                 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                 <button type="button" class="btn btn-primary" id="btnOK">Save</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

模态脚本

$(document).ready(function() {
    $(".viewdetail").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            url: "/BookStore/SelectProduct",
            data: {"id": id},
            type: 'POST',
            cache: false,
            error: function() {
                alert('error');
            }
        });

        $(".tableSelectProduct").load("/view/backend/selectProduct.jsp");
        $("#modalEditProduct").modal('show');
        $("#btnOK").click(function() {
            $("#modalEditProduct").modal('hide');
        });
    });
});

selectProduct.jsp(想要通过不重新加载主页来更新此内容)

<!-- language: lang-html-->
<table width="100%" border="0" class="table" id="center" align="center">
    <tr>
        <td width="14%"></td>
        <td width="63%">
            <label for="thumbnail">Pic</label>
            <a class="thumbnail">
                <img class="resize" src="/BookStore/images/${productDetail.photo}" id="imgprofile" 
                     data-src="/BookStore/asset/js/holder.js/130x100">
            </a>
        <td width="23%"><span id="titleNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td width="14%"></td>
        <td width="63%">
            <label for="titleNotice">Title</label>
            <input type="text" class="form-control" name="title" 
                   onblur="checkEmpty(this, 'titleNotice')" value="${productDetail.title}"></td>
        <td width="23%"><span id="titleNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">ISBN</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.isbn}" onblur="checkEmpty(this, 'ISBNNotice')">
        </td>
        <td><span id="ISBNNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Catagory</label>
            <input type="text" class="form-control" id="form-control" readonly="true"
                   value="${productDetail.catagory}" name="catagory" onblur="checkEmpty(this, 'ISBNNotice')">
        </td>
        <td>
            <label for="titleNotice"></label>
            <button type="button" class="btn btn-primary" id="addCatagory">
                Change Catagory
            </button>
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Author</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.author}" name="author" onblur="checkEmpty(this, 'authorNotice')"></td>
        <td><span id="authorNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td height="130"></td>
        <td>
            <label for="titleNotice">Detail</label>
            <textarea name="detail" rows="5" class="form-control" id="form-control" 
                      onblur="checkEmpty(this, 'detailNotice')" >${productDetail.detail}
            </textarea>
        </td>
        <td><span id="detailNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Price</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.price}" name="price" onblur="checkEmpty(this, 'priceNotice')">
        </td>
        <td><span id="priceNotice"> * ( required )</span></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <label for="titleNotice">Stock</label>
            <input type="text" class="form-control" id="form-control" 
                   value="${productDetail.quantity}" name="quantity" 
                   onblur="checkEmpty(this, 'stockNotice')"></td>
        <td><span id="stockNotice"> * ( required )</span></td>
    </tr>
</table>

2 个答案:

答案 0 :(得分:1)

看起来你错过了成功财产。

 $.ajax({
        url: "/BookStore/SelectProduct",
        data: {"id": id},
        type: 'POST',
        cache: false,
        success: function(response) {
            //  Add in what to do when ajax call is successful
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('error');
        }

答案 1 :(得分:1)

要找出你的ajax中的真正问题,最好在AJAX调用结构下使用。 最好始终为JQuery AJAX调用维护它。

$.ajax({

    type:         "POST",
    url:          "/BookStore/SelectProduct",
    dataType:     "text/xml",
    data:         "",
    processData:  false,  // default to true will parse data as an Array whereas we send XML
    contentType:  "text/xml",
    async:        false,
    beforeSend: function (request)
    {
        // to set some formats
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {  

        if (XMLHttpRequest.status == 400) {
             // Bad Request
             if (XMLHttpRequest.responseText.indexOf("DOMAIN_NOT_FOUND") != -1) {
              alert('invalid domain');

              return false;
             }
      }
      else if (XMLHttpRequest.status == 401) {
             // User/Pass Invalid
       alert('invalid authentication');
          return false;
      }
      else{
       alert('error'+XMLHttpRequest.responseText);
         return false;
      }
    },
    success: function(xml) {
        /* right your logic here */
        return;  
    }  });

谢谢, 赤拉尼维