• JSON对象和字符串的收发(JS客户端用typeof()进行判断非常重要)


    Ajax前台向后台传递对象:

    数据准备

    将js对象或者json对象转换为json字符串在Ajax传递,在后台中再将json字符串转换为json对象,再转换为java对象或在前端和后端构造一样的数据结构,直接用application/json内容体发送。

    复制代码
     1 var student={
     2     name:"abc",
     3     age:12,
     4     no:"123"
     5 };
     6 
     7     console.log(student);
     8     //将js对象转换为json字符串通过ajax传递,在后台中再将json字符串转换为json对象再转换为java对象
     9 
    10     student = JSON.stringify(student);
    复制代码

    Ajax:前端发送

    复制代码
     1 $.ajax({
     2         url : url,
     3         type : "POST",
     4         data : {
     5                 sendData:"传递下面的json字符串",
     6                 jsonStr: student
     7                 },
     8         async : isAsync,
     9         dataType:data_type,
    10         beforeSend : beforeSendFun,
    11         success : function(return_data) {
    12             successFun(return_data);
    13         },
    14         error : function(XMLHttpRequest, textStatus, errorThrown) {
    15             alert("请求处理失败");
    16         }
    17     });
    复制代码

    后台解析:

    复制代码
    String sendData = request.getParameter("sendData");
    
    if (sendData.equals("传递下面json字符串")){
    
    String jsonStr = request.getParameter("jsonStr");
    
    JSONObject student_json= new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
    Student student = (Student)JSONObject.toBean(student_json,Student.class);//再将json对象转换为Student对象 }
    复制代码

    (1)发端是对象var abc = new { name = "菜鸟教程", site = "http://www.runoob.com" };JSON(abc)

    console.log(ds);

    console.log(typeof (ds));object
    console.log(ds.name);菜鸟教程

    Objectname: "菜鸟教程"site: "http://www.runoob.com"__proto__: Object
    ThemeList.js:24 {"name":"菜鸟教程","site":"http://www.runoob.com"}
    ThemeList.js:27 "{"name":"菜鸟教程","site":"http://www.runoob.com"}"
    ThemeList.js:28 ""{\"name\":\"菜鸟教程\",\"site\":\"http://www.runoob.com\"}""

    (2)发端是字符串  string abc= "{"name":"菜鸟教程","site":"http://www.runoob.com"}";JSON(abc)

    var mm=JSON.parse(""{\"name\":\"菜鸟教程\",\"site\":\"http://www.runoob.com\"}"")
    console.log(typeof (mm));string
    var ll = JSON.parse(mm);object
    console.log(ll.name);菜鸟教程

  • 相关阅读:
    [转]Cordova + Ionic in Visual Studio
    [转]Getting Start With Node.JS Tools For Visual Studio
    TypeScript
    [转]NPOI TestFunctionRegistry.cs
    [转]Cordova android框架详解
    [转]POI : How to Create and Use User Defined Functions
    [转]用NPOI操作EXCEL--通过NPOI获得公式的返回值
    [转]Formatting the detail section to display multiple columns (水晶报表 rpt 一页多列)
    [转]Creating Mailing Labels in SQL Server Reporting Services (rdlc 数据1页 2竖排 显示)
    [转]Tetris(俄罗斯方块) in jQuery/JavaScript!
  • 原文地址:https://www.cnblogs.com/bwdblogs/p/11097378.html
Copyright © 2020-2023  润新知