Access Jersey based RESTful service using jQuery

£可爱£侵袭症+ 提交于 2019-12-05 17:12:44
Alex

After a couple of days of research and experiments I discovered that the problem was in the headers of the response. To be able to use the response from the service, I added custom header field:

"Access-Control-Allow-Origin: *"

New service looks like this:

@Path("/helloworld")
public class HelloWorldResource {


    @GET
    @Produces
    public Response test(){

        return Response.ok("test").header("Access-Control-Allow-Origin", "*").build();
    }
}

you have to set crossDomain to true to make cross domain requests

var serviceAddress = "http://192.168.1.2:9998/helloworld";
        function loadDeviceData(){
            $.ajax({
                dataType:'html',
                type:'GET',
                crossDomain:true,
                cache:false,
                async:false,                    
                url: serviceAddress,
                success: function (data) {
                    alert("Data loaded: " + data);
                },
                error: function (xhr) {
                    alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
                }
            });
        }

UPDATE

if your service required the authentication may be you can do it like this

var serviceAddress = "http://192.168.1.2:9998/helloworld";
            function loadDeviceData(){
                $.ajax({
                    dataType:'html',
                    type:'GET',
                    crossDomain:true,
                    cache:false,
                    async:false,
                    xhrFields: {
                      withCredentials: true
                    },
                    username:'yourUsername', //not sure about the username and password options but you can try with or without them
                    password:'thePass',                    
                    url: serviceAddress,
                    success: function (data) {
                        alert("Data loaded: " + data);
                    },
                    error: function (xhr) {
                        alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
                    }
                });
            }

also use jquery 1.5.1 or higher because the crossDomain and some other options are not available in the earlier versions. For reference see this link http://api.jquery.com/jQuery.ajax/

if you are using a javascript function to replace a typical form submission then pay attention to the fact that you should return false; at the end of your javascript function!

you can check a similar issue here http://forum.jquery.com/topic/jquery-newbie-3-9-2011

actually it is nota a matter of jersey but a matter of javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!