每当我在servlet中打印一些内容并由web浏览器调用它时,它都会返回一个包含该文本的新页面。是否有一种方法可以使用Ajax打印当前页面中的文本?

我对web应用程序和servlet非常陌生。


当前回答

Ajax(也称为Ajax)是异步JavaScript和XML的首字母缩写,是一组用于客户端创建异步web应用程序的相互关联的web开发技术。使用Ajax, web应用程序可以异步地向服务器发送数据,并从服务器检索数据。

下面是示例代码:

一个JSP页面JavaScript函数,通过两个变量firstName和lastName向servlet提交数据:

function onChangeSubmitCallWebServiceAJAX()
{
    createXmlHttpRequest();
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    xmlHttp.open("GET", "/AJAXServletCallSample/AjaxServlet?firstName="
    + firstName + "&lastName=" + lastName, true)
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.send(null);
}

Servlet读取以XML格式发送回JSP的数据(也可以使用文本)。您只需要将响应内容更改为文本并在JavaScript函数上呈现数据。)

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("<details>");
    response.getWriter().write("<firstName>" + firstName + "</firstName>");
    response.getWriter().write("<lastName>" + lastName + "</lastName>");
    response.getWriter().write("</details>");
}

其他回答

我将向您展示一个servlet的完整示例以及如何进行Ajax调用。

在这里,我们将创建使用servlet创建登录表单的简单示例。

文件index . html

<form>
   Name:<input type="text" name="username"/><br/><br/>
   Password:<input type="password" name="userpass"/><br/><br/>
   <input type="button" value="login"/>
</form>

Ajax示例

$.ajax
({
    type: "POST",
    data: 'LoginServlet=' + name + '&name=' + type + '&pass=' + password,
    url: url,
    success:function(content)
    {
        $('#center').html(content);
    }
});

LoginServlet servlet代码:

package abc.servlet;

import java.io.File;

public class AuthenticationServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
                          throws ServletException, IOException {

        try{
            HttpSession session = request.getSession();
            String username = request.getParameter("name");
            String password = request.getParameter("pass");

            /// Your Code
            out.println("sucess / failer")
        }
        catch (Exception ex) {
            // System.err.println("Initial SessionFactory creation failed.");
            ex.printStackTrace();
            System.exit(0);
        }
    }
}

使用Bootstrap多选择:

Ajax

function() { $.ajax({
    type: "get",
    url: "OperatorController",
    data: "input=" + $('#province').val(),
    success: function(msg) {
    var arrayOfObjects = eval(msg);
    $("#operators").multiselect('dataprovider',
    arrayOfObjects);
    // $('#output').append(obj);
    },
    dataType: 'text'
    });}
}

在Servlet

request.getParameter("input")

通常不能从servlet更新页面。客户端(浏览器)必须请求更新。客户端要么加载一个全新的页面,要么请求更新现有页面的某个部分。这种技术称为Ajax。

Ajax(也称为Ajax)是异步JavaScript和XML的首字母缩写,是一组用于客户端创建异步web应用程序的相互关联的web开发技术。使用Ajax, web应用程序可以异步地向服务器发送数据,并从服务器检索数据。

下面是示例代码:

一个JSP页面JavaScript函数,通过两个变量firstName和lastName向servlet提交数据:

function onChangeSubmitCallWebServiceAJAX()
{
    createXmlHttpRequest();
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    xmlHttp.open("GET", "/AJAXServletCallSample/AjaxServlet?firstName="
    + firstName + "&lastName=" + lastName, true)
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.send(null);
}

Servlet读取以XML格式发送回JSP的数据(也可以使用文本)。您只需要将响应内容更改为文本并在JavaScript函数上呈现数据。)

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("<details>");
    response.getWriter().write("<firstName>" + firstName + "</firstName>");
    response.getWriter().write("<lastName>" + lastName + "</lastName>");
    response.getWriter().write("</details>");
}
$.ajax({
    type: "POST",
    url: "URL to hit on servelet",
    data: JSON.stringify(json),
    dataType: "json",
    success: function(response){
        // We have the response
        if(response.status == "SUCCESS"){
            $('#info').html("Info  has been added to the list successfully.<br>" +
            "The details are as follws: <br> Name: ");
        }
        else{
            $('#info').html("Sorry, there is some thing wrong with the data provided.");
        }
    },
    error: function(e){
        alert('Error: ' + e);
    }
});