1.在Controller层实现jsonp接口
/**
*Project Name: gspReceiveServer
*File Name: EquipmentController.java
*Package Name: com.ltmap.platform.equipment.controller
*Date: 2016年8月3日 上午9:46:35
*Copyright (c) 2016,578888218@qq.com All Rights Reserved.
*/
package com.ltmap.platform.equipment.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ltmap.platform.equipment.service.EquipmentService;
/**
*Title: EquipmentController<br/>
*Description:
*@Company: 青岛励图高科<br/>
*@author: 刘云生
*@version: v1.0
*@since: JDK 1.7.0_80
*@Date: 2016年8月3日 上午9:46:35 <br/>
*/
@Controller
public class EquipmentController {
@Autowired
EquipmentService equipmentService;
@RequestMapping(value = "updateEquipment", method ={RequestMethod.POST,RequestMethod.GET}, produces = "application/json; charset=utf-8")
@ResponseBody
public int updateEquipment(){
return equipmentService.updateEquipment();
}
@RequestMapping("updateEquipmentJsonp")
public void get(HttpServletRequest request,HttpServletResponse response) {
int flag=equipmentService.updateEquipment();
response.setContentType("text/plain");
String callbackFunName =request.getParameter("<span style="color:#ff6666;">callbackparam</span>");//得到js函数名称
try {
response.getWriter().write(callbackFunName + "([ { flag:\""+flag+"\"}])"); //返回jsonp数据
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.利用ajax进行jsonp的跨域请求
$.ajax({
url: jsonpUrl,
type: 'POST',
dataType: 'jsonp',
jsonp: '<span style="color:#ff0000;">callbackparam</span>',
jsonpCallback:'jsonpCallback',
success: function(json){
console.log("请求路径:"+jsonpUrl+"返回结果:"+json);
console.log(json);
},
error: function(){
// alert('fail');
}
});
3.注意:红字参数名称要保持一致