【问题标题】:Can only get HTML code using ajax, jquery只能使用ajax、jquery获取HTML代码
【发布时间】:2012-12-10 04:03:25
【问题描述】:

我只能用 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”,但它不起作用。

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

【问题讨论】:

  • 然后从 login.jsp 中删除所有的 html
  • 但我没有响应 html 对吧?我只是打印出用户名...
  • &lt;% ... %&gt; 之外的所有内容都将在响应中。
  • 我删除了 之外的所有内容,但仍然得到文本和许多空格。因此,我无法确定响应是否等于用户名...非常感谢您的帮助.. 很奇怪,我应该能够只得到文本结果吗?
  • 只要你使用 jQuery,请查看$.trim

标签: jquery ajax text return-value


【解决方案1】:

在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
        }
    }

});
}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2013-11-19
    • 1970-01-01
    相关资源
    最近更新 更多