AJAX JSONP与新泽西/ JAX-RS RESTful服务新泽西、JSONP、AJAX、RESTful

2023-09-10 14:23:20 作者:温一盏杏花酒

我读了很多关于计算器的问题,但我一直没有得到解决我的问题。

I've read a lot of questions on stackoverflow but i've not got solution to my problem.

这是我的RESTful服务:

This is my Restful service:

@GET
@Path("/GetAllProducts")
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() {        
    return  "{\"name\":\"MAC\", \"quantity\":\"10\"}";
}

它工作正常的浏览器,但是当我使用AJAX,它并没有显示错误,但表现出了弹出:未能对象[对象]

It works fine on browser but when i used AJAX, it didn't display errors but showed a popup: Failed object[Object]

和我的AJAX code:

And my AJAX code:

$.ajax({
    url: "http://localhost:8080/Restful/REST/WebService/GetAllProducts",
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    success: function() { 
        alert("Success"); 
    },
    error: function(e) { 
        alert('Failed! ' + e); 
    }
});

我想补充说:跨域:真,但没有奏效。

I tried to add: "crossDomain: true" but it didn't work.

请帮帮我!谢谢!

推荐答案

首先让我来解释某些方面,我们可以调试这个..

First let me explain some ways we could debug this..

在AJAX调用更改错误功能。第一个参数实际上是 jqHXR 对象,而不是错误消息。这些参数真的去 jqhxr,状态,ERRORMSG 。因此,如果我们使用的功能:

Change the error function in the AJAX call. The first argument is actually the jqHXR object, not the error message. The arguments actually go jqhxr, status, errorMsg. So if we used the function:

error: function(jqxhr, status, errorMsg) {
    alert('Failed! ' + errorMsg);
}

我们会看到这样的警告:

we would see this alert:

并没有真正在这种情况下帮助,如果你不知道这意味着什么,但有时它是有帮助的。

Doesn't really help in this case if you don't know what it means, but sometimes it's helpful.

检查服务器日志 JAX RS 和 Spring 整合开发

Check the server log

在这种情况下,服务器日志不显示意思的请求被成功处理,并且响应被返回的任何错误。

In this case the server log doesn't show any errors meaning the request was processed successfully and the response was returned.

使用浏览器的开发工具。对于Firefox,你应该安装萤火虫。你可以看到请求和所有的标题和这样 Use a browser development tool. For Firefox, you should install Firebug. You can see the request and all the headers and such

您可以看到请求被制成了回调查询参数。同时密切关注接受头,其内容为应用程序/ JavaScript的

You can see the request is being made with a callback query parameter. Also pay close attention to the Accept header, which reads application/javascript

Chrome浏览器有相同类型的工具,并AFAIK,它是内置的,你可以找到它在开发工具。

Chrome has the same type of tool, and AFAIK, it is built in, and you can find it under Developer Tools.

有错误来自于的dataType 在你的AJAX请求设置。 JSONP是不一样的JSON。 JSONP是从,是为了通过前端处理服务器发回的Javascript code。因此,jQuery的期待JSONP格式,这就是为什么它集的标题的应用程序/ JavaScript的,这就是为什么语法错误消息,作为JSON格式是不一样的语法JSONP

There error comes from the dataType setting in your AJAX request. JSONP is not the same a JSON. JSONP is Javascript code sent back from the server that is meant to be processed by the front end. So jQuery is expecting JSONP format, that's why it set's the headers the application/javascript and that's why the "Syntax Error" message, as JSON format is not the same syntax as JSONP.

因此​​,要解决这个问题,你只是单纯的需要设置的dataType JSON

So to fix it, you just simply need to set the dataType as json

dataType: "json",
success: function(data) {
    alert("Success: " + JSON.stringify(data));
},

现在你会看到几件事情:

Now you will see a few things:

当然,成功的消息:

The Success message of course:

请求不再被制成与回调查询参数,因为这是只为JSONP协议。

The request is no longer being made with the callback query parameter, as that is only for the JSONP protocol.

接受头现在用应用程序/ JSON

只是一个仅供参考,的contentType 设置内容类型头。也就是说只有当我们发送的信息,说在一个POST请求非常有用。

Just an FYI, contentType sets the Content-Type header. That is only useful when we are sending information, say in a POST request.

我不知道,如果你的是的期待JSONP outoup,但如果你是,你需要知道的一件事是,JSONP的支持是不是在JAX-RS标准。它dependends的JAX-RS实现,你怎么会需要配置的支持。

I'm not sure if you were expecting JSONP outoup, but if you were, one thing you need to know is that JSONP support is not standard in JAX-RS. It dependends on the JAX-RS implementation, how you will need to configure the support.

首先这里是如何您的AJAX请求应更改为:(或类似的东西)

$.ajax({
    url: "http://localhost:8080/Restful/REST/WebService/GetAllProducts",
    type: 'GET',
    jsonp: 'callback',
    dataType: "jsonp",
    success: function(data) {
        alert("Success: " + JSON.stringify(data));
    },
    error: function(jqxhr, status, errorMsg) {
        alert('Failed! ' + errorMsg);
    }
});

通过JSONP,请求将类似于网​​址是什么?回调= someFunctionToCall ,其中 someFunctionToCall 是服务器环绕的JSON,是我们要调用的我们的JavaScript函数的名称。因此,得到的回答可能会是这样:

With JSONP, the request will look something like url?callback=someFunctionToCall, where someFunctionToCall is what the server wraps around the JSON, and is the name of the our Javascript function we want to be invoked. So the return response might look something like:

someFunctionToCall({"name":"MAC", "quantity":"10"})

使用jQuery的,虽然,我们并不需要发送回调查询参数。它的值将随机地进行。当我测试,这是请求和响应:

With jQuery though, we don't need to send the callback query parameter. Its value will be made at random. When I tested, this was the request and response:

// request
.../GetAllProducts?callback=jQuery20302583482212586644_1418019088133
// response
jQuery20302583482212586644_1418019088133({"name":"MAC", "quantity":"10"})

在返回的响应,我们的成功函数将被调用,传入的数据,将一个正常的反应。上述AJAX请求会提醒完全相同的消息以上。

On return of the response, our success function will be called, passing in the data, as would a normal response. The above AJAX request will alert the exact same message as above.

支持RestEasy的

使用Reasteasy(3.xx的最少),首先要具备RestEasy的杰克逊提供商

With Reasteasy (3.x.x at least), we should first have the Resteasy Jackson provider

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <scope>provided</scope>
</dependency>

我们需要做的是JSONP拦截器添加到我们的部署

All we need to do is add the JSONP interceptor to our deployment

org.jboss.resteasy.plugins.providers.jackson.JacksonJsonpInterceptor

我还没有得到确切的科学,其中下来的媒体类型的需要的这种支持添加,但我和

I haven't gotten the exact science down of which media types need to be added for this support, but I tested with

@Produces({"text/javascript","application/javascript", "application/json"})

对于新泽西2.X

新泽西带有内置的JSONP支持,所以我们不需要任何其他的依赖关系,从​​默认的分配。我们只需要添加 @JSONP 注释。

Jersey comes with built in support for JSONP, so we don't need any other dependencies, from the default distribution. We just need to add the @JSONP annotation.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.glassfish.jersey.server.JSONP;

@Path("/WebService")
public class ProductsResource {

    @GET
    @Path("/GetAllProducts")
    @Produces({"application/json", "application/javascript"})
    @JSONP(queryParam = "callback")
    public String getAllProducts() {
        return "{\"name\":\"MAC\", \"quantity\":\"10\"}";
    }
}

使用相同的jQuery code如上述,将给出相同的结果。多见于含有Padding的JSON支持