springboot restful jsonp 跨域请求
程序员文章站
2022-07-15 16:09:13
...
服务端:
package dd.springboot.demo.controller.userInfo;
import com.google.gson.Gson;
import dd.springboot.demo.models.ZtUser;
import dd.springboot.demo.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class UserInfoController {
@Autowired
UserServices userServices;
@RequestMapping(value = "/user/{id}")
@ResponseBody
public String getUser(@PathVariable("id") Integer id, HttpServletRequest request) {
ZtUser user = userServices.selectByPrimaryKey(id);
Gson gson = new Gson();
String callback = request.getParameter("callback");
String resultValue = callback + "("+gson.toJson(user)+")";
return resultValue;
}
}
客户端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="../Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
type: "Get",
dataType: "Jsonp",
jsonp: "callback",
url: "http://localhost:8080/user/1?callback=?",
success: function (data) {
document.write(JSON.stringify(data));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
})
})
})
</script>
</head>
<body>
<input type="button" value="点我" id="btn" />
</body>
</html>
运行结果: