简体   繁体   English

每次传递错误时都产生Ajax请求(在服务器端jersey / java restful WS中的JSONP中没有应答?)

[英]Ajax request everytime passing through error (not answering in JSONP in server-side jersey/java restful WS?)

I have an API made with Jersey (restful web service), very simple. 我有一个使用Jersey(静态Web服务)制作的API,非常简单。 I have been able to make request/answers through my android application. 我已经能够通过我的android应用程序发出请求/答案。

Now I'm developing a web backend in order to manage data. 现在,我正在开发Web后端以管理数据。 The thing is that when I make calls with ajax, everytime the answer is passing through the "error" part. 问题是,当我使用ajax进行呼叫时,每次答案都通过“错误”部分。

Strange as it may seem, giving a glance to firebug the call/answer seem to be correctly made, with the final 200 OK answer and the right JSON data. 看起来很奇怪,乍看之下似乎可以正确发出呼叫/答案,并带有最终的200 OK答案和正确的JSON数据。

The javascript code is the following: javascript代码如下:

$(document).ready(function (){

        var theUrl = "***url****/Rest/provincias";
        jQuery.ajax({
            beforeSend: function(req) {
                req.setRequestHeader("Accept", "application/json");
            },
            cache: false,
            async: false,
            crossDomain: true,
            type: "GET",
            url: theUrl,
            dataType: "jsonp",
            jsonp: false,
            contentType: "application/json; charset=utf-8",
            statusCode: {
                200: function (data){
                    //OK ANSWER
                    alert("Answer OK: " + data.response);
                }
            },

            error: function (xhr,err) {
                alert("Otra vez en error... " + xhr + "' '" + err);
            },
            success: function (data){
                //Comprobamos en el json si tenemos true o false.

                alert("éxito!! " + data);
            },
            complete: function (xhr, status) {

                if (status === 'error' || !xhr.responseText) {
                    alert("errorrr");
                }
                else {
                    var data = xhr.responseText;
                    alert("Info en complete: " + data);
                }
            }
        });


    });

The JSON text written when I make the call through the browser is similar to this: 通过浏览器进行调用时编写的JSON文本类似于以下内容:

{
  "response": true,
  "data_int": 0,
  "data_boolean": false,
  "data_float": 0.0,
  "data_double": 0.0,
  "data_byte": 0,
  "data_short": 0,
  "data_long": 0,
  "data_char": "\u0000",
  "object": [
  {
  "id": 1,
  "nombreCas": "Ãlava",
  "nombreEus": "Araba",
  "localizacion": {
    "id": 46,
    "latitude": "42.847511",
    "longitude": "-2.679730"
  },
  "pueblos": {
    "1": {
      "id": 1,
      "nombreCas": "Alegría",
      "nombreEus": "Dulantzi",
      "provincia": null,
      "localizacion": {
        "id": 1,
        "latitude": "42.841171",
        "longitude": "-2.512608"
      },
      "barrios": {}
    },

........

As I have been able to read, the error could be because the answer is not in JSONP format (restful WS is answering with a JSON format text), so the line dataType: "jsonp" can't be deleted. 如我所见,错误可能是因为答案不是JSONP格式(宁静的WS正在使用JSON格式的文本进行回答),所以无法删除行dataType:“ jsonp”。 If I delete it, the answer is not made correctly. 如果删除它,答案将不正确。

Is there something to add to my web service? 有什么可以添加到我的Web服务中吗? For example, how to add JSONP support in this code: 例如,如何在此代码中添加JSONP支持:

package main.java.webService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import main.java.model.AccessManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import main.java.dto.Provincia;
import main.java.dto.ReturningClass;

/**
 * @author Jon_Inazio
 *
 */
@Path("provincias")
public class PueblosProvinciasService {

    @GET
    @Produces("application/json")
    public String getProvincias(){
        String provincias = null;
    HashMap<Integer, Provincia> provinciasList = new HashMap<Integer,     Provincia>();
        try{
        provinciasList = new AccessManager().getProvincias();
                GsonBuilder gb = new     GsonBuilder().serializeNulls().setPrettyPrinting(); 
            Gson gson = gb.create();
            Collection<Provincia> arrayProvs = new ArrayList<Provincia>();
        arrayProvs = provinciasList.values();
            /*
             * CONVERTIR HASH MAP A UNA LISTA --> JSON LO PIDE ASI
         */
            //ReturningClass<HashMap<Integer, Provincia>> ret = new     ReturningClass<HashMap<Integer, Provincia>>(true, provinciasList);
            ReturningClass<Collection<Provincia>> ret = new     ReturningClass<Collection<Provincia>>(true, arrayProvs);
            System.out.println("**Se han consultado las provincias!!");
            provincias = gson.toJson(ret);
        }catch(Exception e){
            e.printStackTrace();
    }

        return provincias;
}

}

Thanks in advance and I hope everyone can understand me :). 在此先感谢您,我希望每个人都能理解我:)。

When I write Jersey Web Services I typically have my methods return Response objects. 当我编写Jersey Web Services时,通常让我的方法返回Response对象。 This allows me to include information about the status code and response headers. 这使我可以包含有关状态码和响应头的信息。 This is especially important when making cross domain requests (like it seems you are doing) because it allows you to specify the important response header "Access-Control-Allow-Origin" which enables cross domain requests. 这在发出跨域请求时(如您正在做的事情)尤其重要,因为它允许您指定重要的响应头“ Access-Control-Allow-Origin”,以启用跨域请求。

@GET
@Produces("application/json")
@Path("myPath")
public Response getAllCommissions() {

    // Perform method function
    String json = "OUTPUT_OF_METHOD";

    // Creates a ResponseBuilder
    ResponseBuilder builder = new ResponseBuilderImpl();
    // Sets the header of the return data
    builder.header("content-type", "application/json");
    // Sets the response code as a 200
    builder.status(Response.Status.OK);
    // Allows Cross Domain Requests from any origin
    builder.header("Access-Control-Allow-Origin", "*");
    // Adds your result data to the Response
    builder.entity(json);
    // Creates the Response
    return builder.build();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM