ajax - responseText 包含额外的空白字符(换行,换行),如何在 jsp 中防止和删除它们?

标签 ajax jsp

responseText contains extra whitespace characters (new lines, line feeds), how to prevent and remove them?

请阅读上面的链接

我的 jsp 页面发送 "okay""not",包括空格。 如何防止和删除空格或换行符

valid.js

window.onload=initPage;
function initPage(){
    alert("Browser Started");
    //call checkUsername function
     document.getElementById("username").onblur=checkUsername;
 }
function checkUsername(){
    request=createRequest();
    if(request==null){
        alert("Unable to create request");
    }else{
        alert("Request Object Created")
         var theName = document.getElementById("username").value;
         var username = escape(theName);
         //create url pass username
         var url= "checkName.jsp?username=" + username;
         //any change execute showUsernameStatus function
         request.onreadystatechange = showUsernameStatus;
         request.open("GET", url, true);
         request.send(null);
    }
}
function showUsernameStatus(){
    if (request.readyState == 4) {
        if (request.status == 200) {
            var val=request.responseText;
            alert("Response: "+val);
             if (val == "okay") {
                    //something
                  } else {
                    //something
                  }
        }
    }
}

checkName.jsp

<%@ page language="java"
    pageEncoding="UTF-8"%>
<%String username=request.getParameter("username");
    System.out.println("Username:"+username);
    if(!username.equals("") && username!=null){
        if(!username.equals("Raju")){
            out.print("okay");
            System.out.println("okay");
        }else{
            out.println("not");
            System.out.println("not");
        }
    }
%>

最佳答案

您可以使用 trim()在 Javascript 函数中:

var val=request.responseText;   
if (val.trim() == "okay") {
    // something
} else {
    // something
}

或者您可以使用 trimDirectiveWhitespaces=true在jsp页面中

<%@ page trimDirectiveWhitespaces="true" %>

关于ajax - responseText 包含额外的空白字符(换行,换行),如何在 jsp 中防止和删除它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759023/

相关文章:

javascript - 我有一个 header.jsp,它的样式会随着不同的登录而不断变化,它是一个动态标题

jsp - JSP 中未计算 EL 表达式

java - 我应该如何重定向Spring框架中的第二页

javascript - 重新加载没有 &lt;script&gt; 标签的页面

Javascript/AJAX 元素显示事件

javascript - jQuery:在 ajax 事件后禁用链接的代码遇到问题

java - 使用标签 <sec :authorize> in the jsp pages displaying an error in eclipse

jquery - 通过 $.ajax 请求表单仅返回表单元素

javascript - 为什么这两个相同的字符串在JavaScript中不相等?

java - 使用我的 Java 库将 Android 应用程序连接到本地 MySQL DB