2012-07-05 55 views
0

我正在使用登錄Web服務來驗證用戶。如何使用crossdomain ajax請求發佈數據?

這些是Spring 3.0中的其他web服務,其設計方式是隻接受POST方法的數據。

我能夠使用GET將數據發送到Web服務。

但由於web服務的實現,我必須使用POST方法提交數據。

如果我使用jQuery的ajax請求與POST我得到403訪問禁止的錯誤。

下面是GET請求的工作示例。

我對tomcat使用CORS過濾器來啓用CORS支持。

function callservice() 
    { 
    jQuery.support.cors = true; 
     var mobNo = document.getElementById('mobileNo').value; 
     var acctNo = document.getElementById('accountNo').value; 
     var custNo = document.getElementById('customerId').value; 

     url = url+mobNo+"/"+acctNo+"/"+custNo; 

     $.getJSON(url, 
     function(data) 
     { 
      if (data.authenticated==true) 
      { 
       alert("data "+data); 
      } 
     }); 

} 

但是,如果我使用下面的代碼,我得到403錯誤。

function callservice() 
    { 
     jQuery.support.cors = true; 
     var mobNo = "123123123"; 
     var acctNo = "123123123"; 
     var custNo = "123123123"; 

     var url = "http://localhost/mobile-services/rest/user/";   
     var dataVal = {}; 
     dataVal["mobileNo"] = mobNo; 
     dataVal["accountNo"] = acctNo; 
     dataVal["customerId"] = custNo; 

     var forminput = JSON.stringify(dataVal); 

    $.ajax({ 
     url: url, 
     type: "POST", 
     data:forminput, 
     datatype:"jsonp", 
     crossDomain: true, 
     contentType: "application/json", 
     beforeSend: function() { }, 
     headers : 
     { 
      "Content-Type" : "application/json", 
      "Accept" : "application/json", 
      "Origin" : "http://localhost/", 
      "Access-Control-Allow-Origin" : "*" 
     }, 
     success: function (data) 
     {   
      if (data.authenticated==true) 
      { 
       window.location.replace("http://localhost:8080/mobile-services/selected_services.jsp?userId="+data.id); 
      } 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) 
     { 
      try 
      { 
       alert(JSON.stringify(XMLHttpRequest) + "\n" + textStatus + "\n" + errorThrown); 
      } 
      catch (ex) { alert("Exception occured.. "); } 
      finally { } 
     } 
    }); 
} 

請建議。

+0

這是否幫助:: http://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via- javascript – 2012-07-05 11:54:20

回答