search
HomeWeb Front-endJS TutorialHow front-end and back-end data should interact scientifically

This time I will bring you how to scientifically interact with front-end and back-end data. What are the precautions for front-end and back-end data interaction? Here are practical cases, let’s take a look.

HTML assignment

JS assignment

script fills JSON

AJAX gets JSON

WebSocket real-time transmission of data

Summary

1. HTML assignment output to the value or data-name of Element

<div data-value="<?php echo $user_avatar;?>"></div>

Rendering result

<div data-avatar="https://avatars1.githubusercontent.com/u/3949015?v=3&s=40"></div>

Use JS to get $('input').val();

$(&#39;div&#39;).data(&#39;avatar&#39;);

Advantages: It does not occupy global variables and can be obtained freely by JS.

Usage suggestions: Suitable for
passing simple data, and also very suitable for binding relationships between multiple simple data and Element.

 <li>nimojs <span data-userid="1" >删除</span></li>
  <li>nimo22 <span data-userid="2" >删除</span></li>
  <li>nimo33 <span data-userid="3" >删除</span></li>
  <li>nimo44 <span data-userid="4" >删除</span></li>
  <li>nimo55 <span data-userid="5" >删除</span></li></ul><script>
  $(&#39;span&#39;).on(&#39;click&#39;,function(){ 
    $.post(&#39;/ajax/remove/&#39;,$(this).data(&#39;userid&#39;),function(data){ // ... })
  })</script>

2. JS assignment

Fill data into the
JavaScript variable declaration of <script>. </script>

<script>
  var user_avatar = "<?php echo $user_avatar;?>";
  // 渲染结果
  // var user_avatar = "https://avatars1.githubusercontent.com/u/3949015?v=3&s=40";</script>

Or use Smarty backend

Template engine:

<script>
  var user_avatar = "{$user_avatar}";</script>

Advantages: Passing data is very convenient. The front end directly calls the user_avatar variable to use the data.

Disadvantages:

To transfer a string data, the global variable user_avatar is occupied. When there is a lot of data to be transmitted, many global variables will be occupied.

If there is a newline in the returned data, it will cause a JS error

// The rendering result has a newline character var user_id = "https://avatars1.githubusercontent.com/u/3949015?v=3&s=40" ;// Uncaught SyntaxError: Unexpected token ILLEGAL

Optimization: All content returned by the backend can be stored in a pointed variable, minimizing the use of global variables. Example: // PHP code var SERVER_DATA = { username: {$username}, userid: {$userid}, title: {$title}} // Rendering result var SERVER_DATA = { username: "NimoChu", userid: 1, title : 'F2E'}

Usage suggestions: Use this method when you need to transfer data to JS as quickly as possible and are very sure that the data is stable. If the data format is complex, it is recommended to use script to fill JSON or AJAX to obtain JSON.

3. The script fills JSON****JSON syntax** Fills JSON data into the <script> tag. The front end obtains the JSON string through the DOM and parses it into an object. <p><pre class='brush:php;toolbar:false;'>&lt;script type=&quot;text/template&quot; id=&quot;data&quot;&gt;{&quot;username&quot;:&quot;nimojs&quot;,&quot;userid&quot;:1}&lt;/script&gt;&lt;script&gt; var data = JSON.parse($(&amp;#39;#data&amp;#39;).html()); //{username:&quot;nimojs&quot;,userid:1}&lt;/script&gt;</pre> Advantages: Data can be obtained after the page is loaded. It does not occupy global variables and can pass large amounts of data collections. <p>Disadvantages: When the amount of data is particularly large, the initial loading of the page will be slow. The slowdown is not only caused by the file size, but also because it takes time for the server to query the data and return the collection. You can use AJAX to obtain JSON to complete on-demand loading and load waiting. <br/>Usage suggestions: Suitable for passing large data collections that need to be used when the DOM is loaded. For example: the front-end controls page rendering, and the back-end fills the JSON data source into <script> and the front-end uses a JavaScript template engine to render the page. How to choose a Javascript template engine? <br/>4. AJAX Gets JSON Use AJAX to get JSON data <p><pre class='brush:php;toolbar:false;'>&lt;span id=&quot;showdata&quot;&gt;查看资料&lt;/span&gt; &lt;div style=&quot;display:none;&quot; id=&quot;box&quot;&gt; &lt;h2 id=&quot;用户信息&quot;&gt;用户信息&lt;/h2&gt; &lt;p id=&quot;info&quot;&gt;![](loading.gif)&lt;/p&gt; &lt;/div&gt; $(&amp;#39;#showdata&amp;#39;).on(&amp;#39;click&amp;#39;,function(){ $(&amp;#39;#box&amp;#39;).show(); $.getJSON(&amp;#39;/ajax/userdata/&amp;#39;,function(oData){ // oData = {&quot;username&quot;:&quot;nimojs&quot;,&quot;userid&quot;:1} $(&amp;#39;#info&amp;#39;).html(&amp;#39;用户名:&amp;#39; + oData.username + &amp;#39;&lt;br&gt;用户ID:&amp;#39; + oData.userid); }) })</pre>This is an example of getting user information through AJAX. The process is as follows: <p>Only view information is displayed on the page<p>The user clicks to view information<p>Displays user information and loading pictures<p>Sends to the server to obtain user information AJAX request<p>The server returns a JSON string, $.getJSON automatically converts the returned JSON string into an object<p>Fill the content into <p id="info"><p>Advantages: It does not occupy global variables and DOM nodes, and you can freely control the trigger conditions for obtaining data (when the page is loaded, when the user clicks to view information, or when the user clicks a button). When starting to obtain data, you can use the loading image placeholder to prompt the user that the data is being read. Prevents slow page loading caused by loading all the data on the page. <p>Disadvantages: Additional HTTP requests will be generated. It cannot be obtained immediately after the DOM is loaded. It needs to send a request and receive a response. <p>Usage suggestions: Suitable for loading non-main information, setting trigger conditions (when the user clicks to view data), and providing friendly data reading waiting prompts. <p>5. WebSocket transmits data in real time. If AJAX requests and responses are compared to sending text messages to the server and waiting for the server to reply to text messages, WebSocket is like making a phone call to the server. <p>I won’t introduce much about WebSocket here, but here are the reference materials: <br/><pre class='brush:php;toolbar:false;'>WebSocket**</pre>Building real-time Web applications using HTML5 WebSocket**<p><pre class='brush:php;toolbar:false;'>Ajax vs WebSocket**</pre>6. Summary There is every situation There is no absolutely right way to be useful in situations. Flexibly choose the data acquisition method according to the actual situation. <p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! <p>Related reading: <p><p>Detailed explanation of the box model of html<a href="http://www.php.cn/div-tutorial-387847.html" target="_blank"><br/>##Detailed explanation of the use of bootstrap-validator<p><a href="http://www.php.cn/div-tutorial-387848.html" target="_blank"><br/>How to quickly create html header code in sublime<p><a href="http://www.php.cn/div-tutorial-387846.html" target="_blank"></script>

The above is the detailed content of How front-end and back-end data should interact scientifically. For more information, please follow other related articles on the PHP Chinese website!

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
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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function