springmvc ajax 使用 json 發送請求,處理,並返回

請求是json格式,那麼springmvc返回的格式也必須是json 

不然會出現,返回錯誤,執行error函數

 

首先要用到 json 的jar包


    <!--json轉對象-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

 發送請求

<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script type="text/javascript">
    document.getElementById("submit").onclick=function(){
        var name = document.getElementById("name").value;
        var password = document.getElementById("password").value;
        alert("ks");
        $.ajax({
            url:"user/equale",     //請求地址
            contentType:"application/json;charset=UTF-8",  //傳輸數據類型
            data:JSON.stringify({name:name,password: password}),  //要傳輸的數據
            dataType:"json",   //返回值類型
            type:"post",     //請求方式
            success:function(msg){  //data表示服務端響應的數據
                //在此處讀取返回的msg數據
            },
            complete : function(xhr, status) {
                //攔截器實現超時跳轉到登錄頁面
            }

        });
    }

</script>


https://blog.csdn.net/wangzhiguo9261/article/details/80893244

接收請求,將返回信息轉換成 json 並返回 json

//對比一個用戶(用戶名密碼)
    @RequestMapping(value = "/equale" ,method = RequestMethod.POST)
    public @ResponseBody String  equaleUser(@RequestBody Users user) throws JsonProcessingException {
        System.out.println("對比一個用戶(用戶名密碼)");
        System.out.println(user+"    * * * *user");

        ObjectMapper mapper = new ObjectMapper();
        String str = mapper.writeValueAsString("success");

        return str;
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章