(4)發(fā)布接口

只是寫了最簡單的測試下

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 + "你好!");
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容