<!DOCTYPE html>对应服务器代码示例:
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="jquery.js"></script>
</head>
<script type="text/javascript">
$(function(){
$.ajax({
url:"http://localhost:8080/jsonp/InfoServlet", //请求地址
dataType:"jsonp", //服务器返回的数据类型
data:{name:"Jack"},//向服务器发送的数据
jsonp:"callback", //服务器通过该参数获取jsonpCallback回调函数的名称,名称自定,但是一定要与服务器保持一致。如果没有配置该属性,默认 jsonp:"callback"
jsonpCallback:"myFunc", //自定义的回调函数名。如果没有配置该属性,jQuery会默认生成一个随机函数名
success:function(data, textStatus, jqXHR){ //请求成功
console.info(data.name+data.msg);
//........
},
error:function(jqXHR, textStatus, errorThrown){//请求失败
console.info("error");
//........
}
});
});
</script>
<body>
</body>
</html>
package com.cool.servlet;运行结果:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.cool.vo.User;
@WebServlet("/InfoServlet")
public class InfoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String callBack = request.getParameter("callback"); //对应前端的jsonp:"callback"
String name=request.getParameter("name");
//User user = new User(name,"是个小学生");
//String json = JSON.toJSONString(user);
String json = "{\"name\":\""+name+"\",\"msg\":\"是个小学生\"}";
String jsonpCallBack = callBack + "("+json+")";
response.getWriter().print(jsonpCallBack);
}
}
注意:jsonp只通过get方式向服务器发送请求,即使配置了 type:"POST",也仍然按get方式请求