search
HomeWeb Front-endJS TutorialDetailed explanation of the steps to obtain and load JSON data through JS

This time I will give you a detailed explanation of the steps to obtain and load JSON data through JS. What are the precautions for obtaining and loading JSON data through JS? The following is a practical case, let's take a look.

Detailed explanation of the steps to obtain and load JSON data through JS

When writing pages with repetitive content logic, using json data can significantly improve programming efficiency and facilitate later data processing maintain. Therefore, on the video topic page, multiple columns of video data need to be displayed, and I chose to use json.

The HTML is as follows (only the key parts are shown, JQ needs to be cited)

<p>
    </p><p>
      </p><p>
        </p><p>
          热门视频
        </p>
        <p>
        </p>
      
JS is as follows

<script>
    $(document).ready(function(){
      console.log(1111)
   $.getJSON(&#39;data.json&#39;,function(data){         
            console.log(222)
          var mediahtml="";
          $.each(data,function(i,data) {
          mediahtml+=&#39;<p class="media">&#39;+
          &#39;<p class="media-left">&#39;+
          &#39;<a data-toggle="modal" data-target="#myModal">&#39;+
          &#39;<img class="media-object lazy"  src="/static/imghwm/default1.png"  data-src="&#39;+data["   imgsrc"]+
          &#39;" alt="">&#39;+
            &#39;&#39;+&#39;&#39;+
            &#39;<p class="media-body">&#39;+
            &#39;<p class="title">&#39;+
              &#39;<span class="classify">&#39;+
                data["classify"]+
              &#39;&#39;+
              &#39;<span class="titlename media-heading">&#39;+
                data[&#39;titlename&#39;]+
              &#39;&#39;+
            &#39;&#39;+
            &#39;<span class="time">&#39;+
              &#39;<span class="glyphicon glyphicon-time"> &#39;+
              &#39;<span>&#39;+data[&#39;pubdate&#39;]+&#39;&#39;+
            &#39;<p>&#39;+data["intro"]+&#39;&#39;+
            &#39;<p class="guest">&#39;+
              &#39;<span class="jia">嘉&#39;+
              &#39;<span class="name">&#39;+data["name"]+&#39;&#39;+
              &#39;<span class="position">&#39;+data["position"]+&#39;&#39;+
              &#39;<span class="glyphicon glyphicon-eye-open">&#39;+
              &#39;<span class="click-rite">&#39;+
            &#39;&#39;+
          &#39;&#39;+
            
          &#39;<p class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">&#39;+
            &#39;<p class="modal-dialog" role="document">&#39;+
              &#39;<p class="modal-content">&#39;+
                &#39;<p class="modal-header">&#39;+
                  &#39;<button type="button" class="close" data-dismiss="modal" aria-label="Close">&#39;+
                    &#39;<span aria-hidden="true">×&#39;+
                  &#39;&#39;+
                &#39;&#39;+
                &#39;<p class="modal-body">&#39;+
            &#39;&#39;+
          &#39;&#39;+
          &#39;&#39;
//          var url_mobi=data.url_mobi;
//          var url_pc=data.url_pc;
//          if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
//              $(&#39;.modal-body&#39;).prepend(url_mobi);
//              }else{
//              $(&#39;.modal-body&#39;).prepend(url_pc);
//              }    
              })
          $(&#39;.medialist&#39;).after(mediahtml);        
        }) 
        })
        $(&#39;#myModal&#39;).on(&#39;shown.bs.modal&#39;, function (e) {
          // 关键代码,如没将modal设置为 block,则$modala_dialog.height() 为零 
          $(this).css(&#39;display&#39;, &#39;block&#39;);
          var modalHeight = $(window).height() / 2 - $(&#39;#myModal .modal-dialog&#39;).height() / 2;
          $(this).find(&#39;.modal-dialog&#39;).css({
            &#39;margin-top&#39;: modalHeight
          });
        });
        //点击预览图时判断
//        $(&#39;.modal&#39;).on(&#39;click&#39;, function () {
//          if ($(&#39;#myModal&#39;).css("display") == "none") {
//            $(&#39;.modal-body&#39;).children(&#39;iframe&#39;).attr(&#39;src&#39;, &#39;&#39;);
//          } else {
//            $(&#39;.modal-body&#39;).children(&#39;iframe&#39;).attr(&#39;src&#39;,
//              &#39;https://v.qq.com/iframe/player.html?vid=v0508nqkm75&tiny=0&auto=0&#39;);
//          }
//        })
    
  </script>
You don’t have to read the annotation part, it won’t affect the content.

First, you need to create a new json file. The problem you need to pay attention to with the json file is that json has requirements for the data format and does not recognize various symbols in the url, so an error will be prompted. If not repaired, the JS process will be blocked, causing the data to be lost on the page. It is not displayed. I have been looking for this problem for a long time before I found it, and the json problem will not report an error in js. The solution is to use the encode method to format the url, and then add it to json. You should also use decode to convert it back in html.

The second pitfall is to insert html into a certain tag. There are four methods. You can use after to achieve this. Don't use it the other way around.

The third point is that you need to pay attention. Don’t forget the plus sign when splicing

string. One missing one will cause problems. It will take a long time to find a small problem, and JS will not report an error when splicing errors. It is very difficult. Discover.

The above is how to get JSON data and load it.

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!

Recommended reading:

How to use JS and ajax homology strategy in the project

How to implement track playback in canvas

The above is the detailed content of Detailed explanation of the steps to obtain and load JSON data through JS. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.