Home Web Front-end JS Tutorial Detailed explanation of the steps to obtain and load JSON data through JS

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

Apr 14, 2018 am 11:40 AM
javascript json Obtain

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 class="container-fluid content ">
    <p class="container neirong">
      <p class="left fl">
        <p class="title">
          热门视频
        </p>
        <p class="medialist">
        </p>
      </p></p>
</p>
Copy after login
JS is as follows

<script>
    $(document).ready(function(){
      console.log(1111)
   $.getJSON('data.json',function(data){         
            console.log(222)
          var mediahtml="";
          $.each(data,function(i,data) {
          mediahtml+='<p class="media">'+
          '<p class="media-left">'+
          '<a data-toggle="modal" data-target="#myModal">'+
          '<img class="media-object" src="&#39;+data["imgsrc"]+
          &#39;" alt="">'+
            '</a>'+'</p>'+
            '<p class="media-body">'+
            '<p class="title">'+
              '<span class="classify">'+
                data["classify"]+
              '</span>'+
              '<span class="titlename media-heading">'+
                data['titlename']+
              '</span>'+
            '</p>'+
            '<span class="time">'+
              '<span class="glyphicon glyphicon-time"></span> '+
              '<span>'+data['pubdate']+'</span>'+
            '<p>'+data["intro"]+'</p>'+
            '<p class="guest">'+
              '<span class="jia">嘉</span>'+
              '<span class="name">'+data["name"]+'</span>'+
              '<span class="position">'+data["position"]+'</span>'+
              '<span class="glyphicon glyphicon-eye-open"></span>'+
              '<span class="click-rite"></span>'+
            '</p>'+
          '</p>'+
            
          '<p class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'+
            '<p class="modal-dialog" role="document">'+
              '<p class="modal-content">'+
                '<p class="modal-header">'+
                  '<button type="button" class="close" data-dismiss="modal" aria-label="Close">'+
                    '<span aria-hidden="true">×</span>'+
                  '</button>'+
                '</p>'+
                '<p class="modal-body"></p>'+
            '</p>'+
          '</p>'+
          '</p>'
//          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))) {
//              $('.modal-body').prepend(url_mobi);
//              }else{
//              $('.modal-body').prepend(url_pc);
//              }    
              })
          $('.medialist').after(mediahtml);        
        }) 
        })
        $('#myModal').on('shown.bs.modal', function (e) {
          // 关键代码,如没将modal设置为 block,则$modala_dialog.height() 为零 
          $(this).css('display', 'block');
          var modalHeight = $(window).height() / 2 - $('#myModal .modal-dialog').height() / 2;
          $(this).find('.modal-dialog').css({
            'margin-top': modalHeight
          });
        });
        //点击预览图时判断
//        $('.modal').on('click', function () {
//          if ($('#myModal').css("display") == "none") {
//            $('.modal-body').children('iframe').attr('src', '');
//          } else {
//            $('.modal-body').children('iframe').attr('src',
//              'https://v.qq.com/iframe/player.html?vid=v0508nqkm75&tiny=0&auto=0');
//          }
//        })
    
  </script>
Copy after login
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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where to get Google security code Where to get Google security code Mar 30, 2024 am 11:11 AM

Google Authenticator is a tool used to protect the security of user accounts, and its key is important information used to generate dynamic verification codes. If you forget the key of Google Authenticator and can only verify it through the security code, then the editor of this website will bring you a detailed introduction on where to get the Google security code. I hope it can help you. If you want to know more Users please continue reading below! First open the phone settings and enter the settings page. Scroll down the page and find Google. Go to the Google page and click on Google Account. Enter the account page and click View under the verification code. Enter your password or use your fingerprint to verify your identity. Obtain a Google security code and use the security code to verify your Google identity.

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

How to install dual SIM on Realme 12 Pro? How to install dual SIM on Realme 12 Pro? Mar 18, 2024 pm 02:10 PM

Although the general operations of domestic mobile phones are very similar, there are still some differences in some details. For example, different mobile phone models and manufacturers may have different dual-SIM installation methods. Erzhenwo 12Pro, a new mobile phone, also supports dual-SIM dual standby, but how should dual-SIM be installed on this phone? How to install dual SIM on Realme 12Pro? Remember to turn off your phone before installation. Step 1: Find the SIM card tray: Find the SIM card tray of the phone. Usually, in the Realme 12 Pro, the SIM card tray is located on the side or top of the phone. Step 2: Insert the first SIM card. Use a dedicated SIM card pin or a small object to insert it into the slot in the SIM card tray. Then, carefully insert the first SIM card.

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

How to get fake future crystal coins How to get fake future crystal coins Mar 22, 2024 am 08:00 AM

Many players want to know how to obtain fake future crystal coins. There are actually four different methods, including purchasing gift packages, completing tasks, producing goods, developing land, etc. Players can choose different ways to earn crystal coins according to their needs. The specific content is as follows: Get up and take a look at this guide on how to obtain fake future crystal coins. Fake Future Guide: How to get Fake Future Crystal Coins 1. Purchase the gift package mall to purchase the crystal coin gift package. 2. Obtained by completing tasks and completing main and side tasks. 3. Produce goods. Produce goods in your home to obtain crystal coins. 4. Developing land can also be obtained by developing land, but the reward is one-time.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

See all articles