this.$http.get(‘url’,{
param1:value1,
param2:value2
}).then(function(response){
// response.data中获取ResponseData实体
},function(error){
// 发生错误
});
this.$http.post(‘url’,{
param1:value1,
param2:value2
},{
emulateJSON:true
}).then(function(response){
// response.data中获取ResponseData实体
},function(response){
// 发生错误
});
步骤:
安装vue-resource模块:cnpm install vue-resource --save
在main.js中引入vue-resource并通过命令Vue.user()使用该插件
在组件里面通过get()方法使用
示例:普通请求
@WebServlet(urlPatterns = “/servlet/vue”)
public class VueServlet extends javax.servlet.http.HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding(“UTF-8”);
response.setContentType(“application/json; charset=utf-8”);
response.setHeader(“Access-Control-Allow-Origin”, “*”); //跨域请求
PrintWriter out = response.getWriter();
List userList = new ArrayList<>();
userList.add(new User(11,“zhangsan”,‘女’));
userList.add(new User(22,“lisi”,‘女’));
userList.add(new User(33,“wanger”,‘女’));
userList.add(new User(44,“mazi”,‘男’));
String json = new Gson().toJson(userList);
System.out.println("json "+json);
out.write(json);
}
}
第一步:安装vue-resource模块,代码如下:
第二步:在main.js中引入vue-resource并通过命令Vue.user()使用该插件
第三步:页面
<button @click=“getData()”>请求数据
示例:
@WebServlet(urlPatterns = “/servlet/vue”)
public class VueServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding(“UTF-8”);
response.setContentType(“application/json; charset=utf-8”);
String callback = request.getParameter(“callback”);
PrintWriter out = response.getWriter();
List userList = new ArrayList<>();
userList.add(new User(11, “zhangsan”, ‘女’));
userList.add(new User(22, “lisi”, ‘女’));
userList.add(new User(33, “wanger”, ‘女’));
userList.add(new User(44, “mazi”, ‘男’));
String json = new Gson().toJson(userList);
System.out.println("json " + json);
out.write(callback + “(” + json + “)”);
}
}