0

我只能使用 HTML 标签获得结果,但我只想要文本结果。我的js是:

    $("#login").click(function() {
    var u = $("#username").val();
    var p = $("#password").val();
    //alert(u+" "+p);

    $.ajax({
        type:'POST',
        url:'login.jsp',
        data:'username='+u+'&password='+p,
        dataType:'text',
        success:function(data, status, xhr){
            alert(data);
        }

    });

login.jsp 是:

<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="Database.DB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/plain; charset=utf-8" />
</head>
<body>      
<%
    //get all parameters
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    if(true)
        out.print(username);
    else
        out.println("");
%>
</body>
</html>

但是警报只是给了我一个 html 代码,但是,我只需要“文本”部分。已经将 dataType 设置为“text”,但它不起作用。

请,任何帮助,真的很感激!

4

1 回答 1

0

在 ajax 请求的回调函数中,如果你想要 html 标签中的特定文本,你必须执行以下操作(以登录场景为例)

$("#login").click(function() {
    $.ajax({
    type:'POST',
    url:'login.jsp',
    data:{username:$("#username").val(), password:$("#password").val()},
    dataType:'text',
    success:function(data, status, xhr){
        //to find the text inside the body tag, first we have to 
        //check if there are a body tag using a regular expression.
        var matchBodyTagText = data.match(/<body[^>]*>([\s\S]*?)<\/body>/ig);
        if(matchBodyTagText){
            // The body tag exists, now we have to get only the text inside. 
            // There are described two ways to extract the text inside, but may be there are many other ways

            // 1 : with split, slice and join native methods in Javascript
            console.log(matchBodyTagText[0].split("<body")[1].split(">").slice(1).join(">").split("</body>")[0]);
            // 2 : With JQuery
            console.log($(matchBodyTagText[0]).text());
        }else{
            //Do something else
        }
    }

});
}

我希望是有帮助的。

于 2015-05-27T20:42:27.963 回答