![](/img/trans.png)
[英]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.