简体   繁体   中英

How to compare result of the sucess function with a string when the dataType used to make ajax call to webservice is “jsonp”

I am calling a RESTful webservice using JQuery

I want to compare the response returned from the success function to a string using if-else structure

Note: The response from the RESTful webservice is JSONObject :- "Welcome User"

Here is my code:

            $("#loginform").submit(function(event){

            event.preventDefault();

            var user = document.getElementById("username").value;
            var pass = document.getElementById("password").value;

        $.ajax({
            url: "http://ec2-xx-xxx-xxx-xx.compute-1.amazonaws.com:8080/UserManagement/rest/user_details/sign_in",
            type: "POST",
            crossDomain: true,
            dataType: 'jsonp',
            data: { username: user, password: pass},
            success: function (result) {
            resultDiv.innerHTML=result;

            if (result.toString() == "Welcome User")
            {
                //link to direct to homepage
            }
                            else alert("Invalid details");

            },
            error: function (xhr, ajaxOptions, thrownError) {
            }
        });

Please look at the if-else part and suggest me how to compare the response to string?

If the result of your ajax call is a JSON object, then you won't be able to check for deep equality that way. You will need to find the key index of the string value "Welcome User".

If you're unsure of the data coming in, you can always loop through the JSON object and check for "Welcome User" like so in your success callback :

var containedString = false;
for (var key in results) {
  if (results[key] === "Welcome User") {
    containedString = true;
  }
}

if (containedString = true) {
  // link to homepage
} else {
  alert("Invalid Details");
}

As a side note, always use triple === in javascript as it is safer!

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