【问题标题】:Calling Java Rest API from javascript as JSONP returns invalid label error从 javascript 调用 Java Rest API 作为 JSONP 返回无效标签错误
【发布时间】:2013-10-01 20:38:15
【问题描述】:

我创建了一个 java webservice 来返回国家/地区列表

@RequestMapping(value = "/getcountrylist", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody
@ApiIgnore
Object getcountrylist(@RequestParam String pvtToken,
        @RequestParam String lan) {

    System.out.println(API_TAG + "Request recevied to get CountryList");
    System.out.println("DB:"+dbName);
    if (!this.pvtToken.equals(pvtToken)) {
        CountryList countryList = new CountryList();            
        return new ResponseEntity<CountryList>(countryList,
                HttpStatus.UNAUTHORIZED);
    }
    CountryList countryList = avlMobileAPIService.getCountryList(lan);      
    return new ResponseEntity<CountryList>(countryList, HttpStatus.OK);     

}

我需要从 javascript 调用上述 webservice 作为 JSONP,我编写了以下 javascript 代码如下

function buttonClick(){

$.ajax({
           type: "GET",
           dataType: "jsonp",         
           crossDomain: true,
           url: "http://localhost:8080/api/getcountrylist",
             data: {pvtToken:"JXku56AE0067YtRUSAZEE",lan:"en"},
             Accept: "application/jsonp",
             jsonpCallback:  function(data, status){
                alert('callback');
                alert(data);
           },              
           success: function(data, status){
                alert('sucess');
           },


           });

}

以上函数调用webservice并返回列表,但在客户端显示“invalid label error”。

{"countrylist":[{"countryId":"4","countryCodeAlpha2":"AF","countryCodeAlpha3":"AFG","countryName":"Afghanistan ","isdCode":"93"},{"countryId":"5","countryCodeAlpha2":"AL","countryCodeAlpha3":"ALB","countryName":"Albania ","isdCode":"355"},{"countryId":"6","countryCodeAlpha2":"DZ","countryCodeAlpha3":"DZA","countryName":"Algeria ","isdCode":"213"},{"countryId":"7","countryCodeAlpha2":"AS","countryCodeAlpha3":"ASM","countryName":"American Samoa ","isdCode":"684"}]}

我在一些文章中发现它说,ajax 调用需要 JSONP ,但返回 JSON 数据。

解决办法是什么?

【问题讨论】:

  • 我也尝试在 ajax 调用中使用以下属性 - 接受:“application/json”,contentType:“application/json”,但结果相同。
  • REST API 真的支持 JSONP 吗? (例如:返回带有在客户端执行的尾随 javascript 代码的 JSON 响应)。如果没有,那么您可能只想在 .ajax 方法中使用 success 回调。从您的示例来看,它看起来像普通的 JSON,而不是 JSONP
  • 我不知道,我应该在 java 端做什么来支持 JSONP。我尝试了很多例子。
  • 你不需要。只需将现有的JSON 响应与.ajax 中的success 回调一起使用。将 dataType 更改为 json 并为您解析结果,并将对象作为第一个参数返回给 success 回调。
  • 我尝试使用以下代码 $.ajax({ type: "GET", dataType: "json", url: "localhost:8080/api/mobile_getcountrylist", data: {pvtToken:"JXku56AE0067YtRUSAZEE",lan: "en"}, contentType: "application/json", 成功: function(data, status){ alert('sucess'); }, });返回错误“NetworkError:500 内部服务器错误 - localhost:8080/api/…

标签: java api rest jsonp


【解决方案1】:

参考这个链接 http://www.iceycake.com/2012/06/xml-json-jsonp-web-service-endpoints-spring-3-1/

或者用这种简单的方法试试

@RequestMapping(value = "/mobile_getcountrylist", method = RequestMethod.GET, produces = {"application/x-javascript"})
    @ResponseBody   
    public Object mobile_getcountrylist( @RequestParam("callback") String jsonpCallback) {

        System.out.println(API_TAG + "Request recevied to get CountryList");    
        CountryList countryList = avlMobileAPIService.getCountryList("en");
        //countryList.setJsonCallback(jsonpCallback); 
        return convertToJsonP(countryList,jsonpCallback);
    }

    private String convertToJsonP(Object o,String jsonpCallback){
        String outputmessage=null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            outputmessage=mapper.writeValueAsString(o);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(outputmessage!=null){
            outputmessage=jsonpCallback + "(" + outputmessage + ")";
        }
        return outputmessage;   
    }

Javascript 代码

$.ajax({
        type: 'GET',
        url: 'http://localhost:8080/api/mobile_getcountrylist',
        crossDomain: true,
        async: false,
        jsonpCallback: 'jsonpCallback',
        dataType: 'jsonp',
        contentType:'application/json',
        success: function(data) {        
         alert('ok');
        }
    });

【讨论】:

  • 嗨,我知道这篇文章很旧,但它对我帮助很大! +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多