- get方式
this.$http.get(‘url’,{
param1:value1,
param2:value2
}).then(function(response){
// response.data中获取ResponseData实体
},function(error){
// 发生错误
});
- post方式
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模块,代码如下:
cnpm install vue-resource --save
第二步:在main.js中引入vue-resource并通过命令Vue.user()使用该插件
import VueResource from ‘vue-resource’;
Vue.use(VueResource);
第三步:页面
<button @click=“getData()”>请求数据
- {{item}}
-
- 服务器端代码:
@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 + “)”);
}
}