[英]How to make post ajax call with JSON data to Jersey rest service?
[英]Ajax post call to a rest service through servlet
我有一個小問題:我正在開發jQuery Mobile應用程序,我需要對rest服務進行ajax發布。 我使用servlet動態創建頁面。
我試圖對其余URL進行ajax調用:
http://localhost:8181/myRestServicePath/func?key=value
在頁面上輸入以下網址:
http://localhost:8080/Mypage
但是我從瀏覽器中收到一個跨源錯誤。
因此,我正在嘗試執行此調用,並使用doPost()方法通過Java servlet。
現在,我的意圖是從發出ajax帖子
http://localhost:8080/Mypage
至:
http://localhost:8080/myServletPath/func?key=value
並且此servlet應該將POST請求重定向到我的RestService:
http://localhost:8181/myRestServicePath/func?key=value
我如何執行此重定向?
可能有幾種方法可以實現這一目標。 我只分享以下兩種常見的可能性。
對於POST請求:-您將需要在servlet中使用Apache HTTPClient將請求發送到Web服務並獲得響應。 收到響應后,您可以將該響應發送到您的頁面。
對於GET請求:
對於跨域請求,您不需要額外的servlet。 您可以使用JSONP
jQuery示例:
$.ajax({
url:"http://localhost:8080/myServletPath/func?key=value",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
有關后端示例,請訪問Java J2EE跨域JSONP教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.