【问题标题】:Simple AJAX Servlet with Callback带有回调的简单 AJAX Servlet
【发布时间】:2013-03-07 11:28:52
【问题描述】:

我正在尝试学习 AJAX,现在我正在阅读 servlet 和回调。我觉得我的书没有详细介绍 servlet 或回调,所以我查看了许多在线资源,结果更加困惑。我觉得我会通过实例来理解它,所以我指望你们帮助我:) 将不胜感激!我要做的是创建一个接受数字的索引页面,将其异步传递给 servlet 以求平方,然后在索引页面上显示结果。这是我到目前为止所得到的。

index.html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script>
            function setup() {
                if (window.XMLHttpRequest) {
                    r = new XMLHttpRequest();
                } else {
                    r = new ActiveXObject("Microsoft.XMLHTTP");
                }
                r.open("get","convert",true);
                r.onreadystatechange=???????????
                r.send(null);
            }
        </script>
    </head>
<body onload="setup()">
    <h3>Enter a number to be squared <input type="text" name="number" size="2" 
        maxlength="4"/></h3>
    <p id="result"></p>
</body>

转换.java

package squared;

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;
import java.sql.*;

public class convert extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/xml"); 
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out=response.getWriter();

    }
}

感谢您抽出宝贵时间帮助我!

【问题讨论】:

    标签: ajax servlets asynchronous


    【解决方案1】:

    如果我们使用 Jquery,使用 Ajax 确实很容易,但我们应该学习如何创建 XMLHttpRequest 对象。我提供了一个简单的 ajax 示例,希望对您有所帮助。 在您提出的问题中,我找不到您的 servlet 正在从请求对象中读取任何内容并将结果发送回任何响应。 HTML 文件:(index.html)

    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Servlet Test</title>
    </head>
    <body>
    <h3>Please enter a number to Square : </h3>
    <input type="text" id="numberToSquare">
    <input type="button" onclick="callServlet();" value="Click To Square">
    <div id="result"></div>
    </body>
    <script>
    function callServlet()
    {
        var xmlhttp;
        var input = document.getElementById('numberToSquare').value;
        if (window.XMLHttpRequest)
        {
        // This part is mainly for the latest browsers which have XMLHttpRequest object
            // like Chrome,Firefox,Safari and IE7+
        xmlhttp=new XMLHttpRequest();
        }
        else
        {
        // This should take care of the older browsers
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    xmlhttp.onreadystatechange=function()
    {
    /*
    readyState has four different states : 
        0: request not initialized 
        1: server connection established
        2: request received 
        3: processing request 
        4: request finished and response is ready
    status is ranging between 200 - Ok and 404 - Page Not Found     
    */
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("result").innerHTML=xmlhttp.responseText;
    }
    }
    xmlhttp.open("GET","ServletTest?val="+input,true);
    xmlhttp.send();
    }
    </script>
    </html>
    

    使用的 servlet:(我只提供 doGet 方法,因为 servlet 的其余部分都很好)

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
    ServletException, IOException {
        // TODO Auto-generated method stub
        String val = request.getParameter("val");
        int valFromString = Integer.parseInt(val);
        Double d =  Math.pow(valFromString, 2);
        PrintWriter writer = response.getWriter();
        writer.println(d);
        System.out.println(d);
    }
    

    【讨论】:

      【解决方案2】:

      我认为使用jQuery.ajax 方法而不是手动创建XMLHttpRequest 对象更容易且不易出错。 http://api.jquery.com/jQuery.ajax/

      但是如果你想让你的 XMLHttpRequest 工作,你应该执行以下步骤:

      1. 通过new操作符创建新的XMLHttpRequest对象;
      2. 在您的 XMLHttpRequest 上调用方法 open
      3. 定义onload回调函数;
      4. 调用XMLHttpRequest的methidsend向服务器发送请求。

      代码应如下:

      var XHR = new XMLHttpRequest();
      XHR.open('GET', 'some-url', true);
      XHR.onload = function() {
         // here is function body
      };
      XHR.send();
      

      在服务器端,您应该将您的 servlet 映射到 'some-URL',您将在 AJAX 调用中使用它。 您可以在项目的web.xml 文件中执行此操作。

      【讨论】:

      • 我同意你关于 jQuery 的观点,但我看过的大多数书籍/参考指南都建议在学习 jQuery 之前先学习如何创建 XMLHttpRequest 对象。不过还是谢谢你的推荐。我最终会学会的,哈哈。
      猜你喜欢
      • 2011-05-06
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      相关资源
      最近更新 更多