简体   繁体   中英

Cannot compare String returned by out.print()

I am using jsp as a server side script with HTML/JQuery for the client end. I am doing a AJAX to the jsp file and everything works ok. The problem starts when I am trying to compare the string returned by out.print() from jsp with in the jquery ajax result. The comparison never seems to result true!

It seems the out.print() is prepending a number of /n to the string.

$.post("jsp/login.jsp", { msg: $email.val() + "~" + $pass.val() }, function (result) {
    if (result === "OK") 
        alert("Logged in");
    else
        alert("Invalid Credentials");
});

It seems the out.print() is prepending a number of /n to the string.

In this case you have two options. First, you can remove the extra whitespace in JS before using the value in a condition:

if ($.trim(result) === "OK") 
    alert("Logged in");
else
    alert("Invalid Credentials");

Alternatively, and preferably, you could change your JSP code to return JSON. By definition this cannot have extraneous whitespace added to the values of its properties.

Remember how Java object comparisons work. In java a string literal "OK" in this case is itself an object and has it's own location in memory. When you do a comparison with another string object, result in this case, you aren't comparing the actual value of the two strings as you would with primitive types you're comparing the object location in memory. As such, you could use something like compareTo which is associated with String, something like this.

//Compare to returns an int, -1 for less then, 1 for greater then and 0 for equals

if(result.compareTo("OK") == 0){
//Do your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM