java jsonp接口_通过JSONP实现ajax跨域请求java接口实现

用jsonp实现跨域

@ApiOperation(value = "Test vehicle param info")

@RequestMapping(method = RequestMethod.GET, value = {

"/api/1.0/ups/test",

}, produces = APPLICATION_JSON_UTF8_VALUE,headers ={"Accept=" + APPLICATION_JSON_UTF8_VALUE})

public void test(HttpServletRequest request, HttpServletResponse response)throws Exception{

response.setContentType("text/plain");

response.setHeader("Pragma", "No-cache");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

response.setHeader("Access-Control-Allow-Origin", "*");//添加跨域访问

Map result = new HashMap();

Map data=new HashMap();

ObdParam param=obdParamRepository.getParams().get(0);

data.put("obdParam",param);

String jsonpCallback = request.getParameter("callback");//客户端请求参数

try {

// String test=request.getParameter("test");

result.put("errorCode", "0");

result.put("errorMessage","success!");

result.put("data",data);

} catch (Exception e) {

e.printStackTrace();

}finally {

PrintWriter out = response.getWriter();

Gson gson=new Gson();

String json = gson.toJson(data);

// JSONObject resultJSON = JSONObject.fromObject(result); //根据需要拼装json

// out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据

System.out.print(jsonpCallback+"("+json.toString()+")");

out.println(jsonpCallback+"("+json.toString()+")");//返回jsonp格式数据

out.flush();

out.close();

}

}

jQuery(document).ready(function(){

$.ajax({

type : "get",

async:false,

url : "http://192.168.0.187:8080/services/api/1.0/ups/test",

dataType : "jsonp",

// data:"{}",

jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)

jsonpCallback:"jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名

success : function(data){

$("#p1").text(data.obdParam.intakePressure);

$("#p2").text(data.obdParam.throttlePosition);

$("#p3").text(data.obdParam.timingAdvance);

$("#p4").text(data.obdParam.engineLoad);

$("#p5").text(data.obdParam.fuelLevel);

$("#p6").text(data.obdParam.vehicleSpeed);

$("#p7").text(data.obdParam.engineRpm);

$("#p8").text(data.obdParam.coolantTemp);

$("#p9").text(data.obdParam.intakeairTemp);

$("#p10").text(data.obdParam.massairRate);

$("#p11").text(data.obdParam.dtc);

},

error:function(XMLHttpRequest, textStatus, errorThrown){

console.error(XMLHttpRequest.status);

console.error(XMLHttpRequest.readyState);

console.error(textStatus);

}

});

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值