簡體   English   中英

jQuery不執行servlet doGet

[英]jQuery not executing servlet doGet

我對Java還是很陌生,並且正在嘗試將解決方案發布在這里: 如何使用Servlet和Ajax? ,但jQuery調用未執行servlet。

Servlet代碼如下:

package com.morley.app;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxTest extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";
    System.out.println("Im working");
    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}
}

我的web.xml映射如下:

<servlet>    
    <servlet-name>AjaxTest</servlet-name>
    <servlet-class>com.test.app.AjaxTest</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>AjaxTest</servlet-name>
    <url-pattern>/AjaxTest</url-pattern>
</servlet-mapping>

而我的jsp如下:

<head>
    <title>SO question 4112686</title>

    <script type="text/javascript" src="<%= request.getContextPath() %>/js/jquery-latest.min.js"></script>

    <script>
        $(document).ready(function() {                        // When the HTML DOM is ready loading, then execute the following function...

            $('#somebutton').click(function() {               // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...

                $.get('AjaxTest', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    //alert('ready');
                    $('#somediv').text(responseText);         // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });

            });    
        });
    </script>

</head>
<body>
    <button id="somebutton">press here</button>
    <div id="somediv"></div>
</body>

如果有人可以幫助我弄清楚doGet為什么不觸發的原因,將不勝感激。

檢查ajax命令是否正在執行並將請求發送到正確的地址。

您可以通過ctrl + shift + c打開控制台窗口並進入網絡來幫助您進行調試,從而在chrome中對其進行檢查。 (Firefox為此有螢火蟲)。

附言:創建ServLet后,重新啟動服務器。 JSP文件是自己啟動的,但是對於servlet,您需要重新啟動服務器以使其啟動並運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM