search
HomeWeb Front-endJS TutorialDetailed explanation of mutual value transfer between front and backend using json_json

If there are too many values ​​​​for mutual value transfer between the front and backend, writing will be cumbersome, tiring, and error-prone. Here is a set of ways to use mark tag attributes to pass values. The backend value acquisition and frontend binding have been greatly simplified.

1. Convert json object into string

Copy code The code is as follows:

$.extend({
//Convert json object into string [It seems that jquery does not have this method]
          toJSONString: function (object) {
                  if (object == null)
                    return;
            var type = typeof object;
If ('object' == type) {
If (Array == object.constructor) type = 'array';
                        else if (RegExp == object.constructor) type = 'regexp';
                     else type = 'object';
            }
switch (type) {
case 'undefined':
case 'unknown':
                    return;
break;
case 'function':
case 'boolean':
case 'regexp':
                           return object.toString();
break;
case 'number':
Return isFinite(object) ? object.toString() : 'null';
break;
case 'string':
return '"' object.replace(/(\|")/g, "\$1").replace(/n|r|t/g, function () {
                      var a = arguments[0];
return (a == 'n') ? '\n' : (a == 'r') ? '\r' : (a == 't') ? '\t' : ""
                                                                                                                 '"'; break;
case 'object':
If (object === null) return 'null';
                  var results = [];
for (var property in object) {
                        var value = $.toJSONString(object[property]);
                         if (value !== undefined) results.push($.toJSONString(property) ':' value);
                     }
                     return '{' results.join(',') '}';
                     break;
                 case 'array':
                     var results = [];
                     for (var i = 0; i                          var value = $.toJSONString(object[i]);
                         if (value !== undefined) results.push(value);
                     }
                     return '[' results.join(',') ']';
                     break;
             }
         }
     });

二、创建数据容器对象 [用来绑定要传给后台的前台控件值]

复制代码 代码如下:

var DataClass = {
Create: function () {
Return function () {
This.myinit.apply (this, arguments); // The constructor of the creation object // Arguments's parameter collection system name cannot be written wrong
                 }
            }
}
var MyDataPack = DataClass.create();
MyDataPack.prototype = {
//Initialization
MyInit: function (url, operation, params) {
This.data = new Object(); //All data capacity
              var bdata = new Object();
                      bdata.url = url;                        bdata.operation = operation;//Operation
                         bdata.params = params; This.data.BasicData = bdata; //Basic data
             },
//Add data such as: addValue("obj", "111");
       addValue: function (p, obj) {
This.data[p] = obj;
},
//Get the values ​​of all mark controls and write data
GetValueSetData: function (togName) {
                   var values ​​= Object(); // Collection of values ​​
                         $("[subtag='" togName "']").each(function () {
//If it is an input type control
If (this.localName == "input") {
//If it is a text control
If (this.type == "text" || this.type == "hidden") {
values[this.id] = this.value;
                                                                                                       }                              else if (this.type == "...") {
                                                                                                       }                                                                                                                                         }
                            else if (this.localName == "...") {
                    }
                                                                                             });
This.data[togName] = values;//Add to data collection
             },
//Value such as: getValue("BasicData")
GetValue: function (p) {
                     return this.data[p];
             },
//Get or set url
GetUrl: function (url) {
If (url)
This.data.BasicData["url"] = url;
                 else
                              return this.data.BasicData["url"];
            }
,
//Convert the value into a string object data
GetJsonData: function () {
            return $.toJSONString(this.data);
}
}

3. Create a bound front-end data object [used to read the value passed from the background and bind it to the front-end page]

Copy code The code is as follows:

var MyDataBinder = {
//Bind data to the control data: data tag: tag
Bind: function (data, Tag) {
         var MJson = $.parseJSON(data);
//Only bind marked tags
           $("[bindtag='" Tag "']").each(function () {
If (this.localName == "input") {
                              if (MJson[this.id]) //If the value is passed in the background
$(this).attr("value", MJson[this.id]);
            }
               else if (this.localName == "...") {
            }
                  //....
        });
}
};

4. Usage examples

Front-end html:

Copy code The code is as follows:



                                                                                                                                                                                                                                                                                                       

           
            
                                                                                                                                                                                                                                                                                                     




Front-end js:

Copy code

The code is as follows:

//====================Usage example========================== ============
var MyDataPack = new MyDataPack("Handler1.ashx", "CESHI", "");
MyDataPack.getValueSetData("subtag");//Write the control data into the object "subtag" is the tag to get the control value
//------------------Transfer the front-end value to the back-end---------------
$.post(MyDataPack.getUrl(), MyDataPack.getJsonData(), function (data) {
//-------------------Bind the background value to the foreground-----------------
MyDataBinder.Bind(data, "bind"); //"bind" is the label
of the control to be bound });

Backstage:

Copy code The code is as follows:

public void ProcessRequest(HttpContext context)
{
Context.Response.ContentType = "text/plain";
//====================Get the foreground value========================== ====================
//Because what is passed in the background is the converted string of json object, so all the data is passed as a parameter
var values ​​= context.Request.Form[0];
//Need to introduce assembly System.Web.Extensions.dll
JavaScriptSerializer _jsSerializer = new JavaScriptSerializer();
//Convert json object string into Dictionary object
Dictionary> dic = _jsSerializer.Deserialize>>(values);
//Now dic contains all the values ​​passed from the front desk, you can use them however you want.
String inp_2 = dic["subtag"]["inp_2"];//In this way, the control value value with the id of inp_2 on the front page is directly obtained
//====================== Pass the value to the front desk======================== =====================
Dictionary dic2 = new Dictionary();
dic2.Add("inp_1", "Modify 1");//Here, just use the corresponding control id to pass the value
dic2.Add("inp_2", "Modify 2");
dic2.Add("inp_3", "Modify 3");
Context.Response.Write(_jsSerializer.Serialize(dic2));
}

Do you guys have a clear understanding of using json to realize front-end and back-end value transfer? If you have any questions, please leave me a message

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.