我创建了一个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调用上面的web服务作为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并返回列表,但在客户端显示“无效标签错误”。
{"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数据。
解决方案是什么?
答案 0 :(得分:4)
提供此链接 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');
}
});