angularjs $http实现get和post请求

来源:互联网 发布:云网络验证 编辑:程序博客网 时间:2024/06/05 21:14

angularjs $http实现get和post请求

本文主要介绍如何通过angularjs的$http实现get和post请求。

好,下面上货。
首先看一下后台的服务。
package com.xueyou.demo.controller;import com.xueyou.demo.pojo.Student;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;import java.util.List;@RestController@CrossOrigin@RequestMapping("/request")public class RequestController {    @RequestMapping(value = "/get", method = {RequestMethod.GET})    public List<Student> getStudentList() {        Student student = new Student(1, "xiaoming");        List<Student> studentList = new ArrayList<>();        studentList.add(student);        return studentList;    }    @RequestMapping(value = "/post", method = {RequestMethod.POST})    public List<Student> postStudentList() {        Student student = new Student(2, "xiaohong");        List<Student> studentList = new ArrayList<>();        studentList.add(student);        return studentList;    }}

然后是angularjs的请求:
biPlateform.controller('mainController', function ($scope, $stateParams, $http) {    $scope.test = "bbb";    var c = $stateParams.id;    console.log(c);    $http.post(Setting.BASE_URL + "/request/post").success(function (data, status, headers, config) {        console.log(data);    }).error(function (data, status, headers, config) {        console.error(data);    });    $http.get(Setting.BASE_URL + "/request/get").success(function (data, status, headers, config) {        console.log(data);    }).error(function (data, status, headers, config) {        console.error(data);    })});

下面看一下调用之后的结果:


注意,在服务端,也就是后台程序一定要加上@CrossOrigin,否则会出现跨域问题。
原创粉丝点击