只是寫了最簡單的測試下
springMvc的@ResponseBody可以直接輸出json數(shù)據(jù)
網(wǎng)頁調(diào)用接口木有問題,但是手機調(diào)用卻出現(xiàn)跨域問題,必須要用jsonp實現(xiàn),后臺實現(xiàn)是getUser()方法
package com.djy.controller;
import com.djy.model.User;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by admin on 2017/5/19.
*/
@Controller
public class MainController {
/**
* @return 處理完該請求后返回的頁面,此請求返回 index.jsp頁面
* @RequestMapping()注解:用于定義一個請求映射,value為請求的url,值為 / 說明,該請求首頁請求,method用以指定該請求類型,一般為get和post;
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "hello";
}
@RequestMapping(value = "/data", method = RequestMethod.GET)
public @ResponseBody String data(){
return "djy33333";
}
@RequestMapping(value = "/userJson", method = RequestMethod.GET)
public @ResponseBody User getUserJson(){
User u = new User("djy", "13072520860", "123456");
return u;
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public @ResponseBody String getUser(String callback){
User u = new User("djy", "13072520860", "123456");
Gson gson = new Gson();
if(callback == null)
return gson.toJson(u);
else
return callback + "(" + gson.toJson(u) +")";
}
}
對應的jquery代碼
function loginReq() {
$.ajax({
url: 'http://192.168.0.164:8081/user',
type: 'get',
dataType: 'jsonp',
jsonpCallback: "loginCallback",
success: function(res) {
alert("success");
location.href = "index.html" + "?title= " + res.name + " ";
return false;
},
error: function(error) {
alert("error");
}
})
}
function loginCallback(json) {
alert(json.name + "你好!");
}