简体   繁体   中英

Trouble handling 302 redirect with jquery ajax

Due to some requirement I need to login to a site using jquery ajax .. but when I try to do so .. the firebug console is saying that it is 302 error. I have tried to implement the code for its handling but unfortunately with no success

Here is my code I have tried till now :

<script type='text/javascript' src='http://code.jquery.com/jquery.js'>
  </script>
  <script type='text/javascript'>


  $(document).ready(function(){


  $.ajax({

  url        : "https://testDomain/login.asp",
  async      : false,
  type       : 'POST',
  data       : {Username:'test',Password:'testPass'},
  success    : function(respText){alert(respText);},

  error      : function (jqXHR, textStatus, errorThrown)
               {
                  console.log(jqXHR.getResponseHeader("Location")); // undefined;
               },

  statusCode: {
               302: function() {
                               alert("page not found");
                             }
              },                
  complete  : function(response) {  
              if(response.status == 302) {  
                  window.alert('page not found');    
              }
   }
       })

  });

  </script>

when I see the response headers they show up as

Date            Wed, 13 Mar 2013 06:43:18 GMT
Location        https://testDomain/pageXXX.asp
Server          Microsoft-IIS/6.0
Set-Cookie      TravAuthV=e;path=/; domain=testDomain.com;
X-Powered-By    ASP.NET

What am I missing .. ?? Or is there any other alternative to handle this

Thanks for your time .. any help will be appreciated...

You are not missing anything problem is in below line.

url        : "https://testDomain/login.asp",

you are sending SSL request using ajax and i don't think its working because it's violates Javascript's policy because it doesn't see the SSL Requested from the same source as the non-SSL url..

What you can do?

you can add the Access-Control-Allow-Origin header from the server.

Access-Control-Allow-Origin: https://testDomain/login.asp

Read More

Try using setting crossDomain : true and dataType:jsonp if not jsonp response then remove it.

$.ajax(
{
    url: 'https://testDomain/login.asp',
    async      : false,
    type       : 'POST',
    data       : {Username:'test',Password:'testPass'},
    success    : function(respText){alert(respText);},
    crossDomain: true,
    dataType: 'jsonp',
    error: function() { alert('Failed!'); },
    beforeSend: function(xhr)
    {
        xhr.setRequestHeader('Authorization',getToken());
    }
});

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