springmvc学习(小知识点整理)

我们客户端经常是会收到服务器返回的json数据这个时候,我们很多时候都是直接使用便可,但有时我们也需要向服务器发送json数据,这个时候获取表单数据并转换为json数据就很有必要了

  • 前台json和json之间的转换
    • Json对象转json字符串使用JSON.striingfy(jsonObj);
      {name:"ggr",age:21} ===> '{"name":"ggr","age":21}'
    • json字符串转JSON对象使用JSON.parse(jsonStr);
      '{"name":"ggr","age":21}' ===> {name:"ggr",age:21}

我们导入了jquery1.8的包,新建一个jsp测试一下

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>" />
<head>
    <script src="${basePath}resources/js/jquery-1.8.3.min.js"></script>
    <title>json.jsp页面</title>
</head>
<script>
    //jsonStr==>json
    var jsonObj = {name:"ggr",age:21};
    console.log(jsonObj);
    var jsonArray = [];
    jsonArray.push(jsonObj);
    jsonArray.push(jsonObj);
    jsonArray.push(jsonObj);
    var jsonStr ='{"name":"ggr","age":21}';
    console.log(jsonStr);
    console.log(jsonArray);
    console.log("-------------------------------");
    console.log(JSON.parse(jsonStr));
    console.log(JSON.stringify(jsonObj));

    console.log("-------------------------------");
</script>
</html>

浏览器运行效果:
运行结果

原文地址:https://www.cnblogs.com/ggr0305/p/7213967.html