Home Web Front-end JS Tutorial Detailed explanation of JavaScript callback function use cases

Detailed explanation of JavaScript callback function use cases

May 22, 2018 pm 03:02 PM
javascript js

This time I bring you JavaScript callbackCallback functionDetailed explanation of use cases, what are the precautions when using JavaScript callback function, the following is a practical case , let’s take a look.

Callback functions are often used when using open source projects. If the callback functions are clarified, it will be of great help to us to understand the open source projects in depth.

Explanation of callback function Baidu Encyclopedia:

The callback function is a function called through the function pointer. If you pass a function pointer (address) as a parameter to another function, and when this pointer is used to call the function it points to, we say it is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs to respond to the event or condition.

It doesn’t seem that easy to understand. Let’s take a look at an example (Zhihu):

You go to a store to buy something, and what you want happens to be out of stock. So you left your phone number with the store clerk. After a few days, the store had the goods, and the store clerk called you. After receiving the call, you went to the store to pick up the goods. In this example, your phone number is called the callback function. When you leave your phone number with the store clerk, it is called the registration callback function. When the store has goods later, it is called the event associated with the callback. When the store clerk calls you, it is called the callback function. When you go to the store to pick up the goods, it is called responding to the callback event.

This is much easier to understand. When the clerk is created, he does not know who will come to the store to buy things. The clerk needs to deal with many different objects and needs to adapt to different types of objects. At this time, a callback function is needed.

Let’s use an example to understand the application scenario of the callback function:

Me needs to complete a task, calculate 1 1=?

If you want to complete this task yourself

The code is as follows:

HTML code

<p class="imgp">
  <p class="search">
    <input class="put" type="text" id="keyWord"/>
    <ul id="tipList"></ul>
</p>
Copy after login

JavaScript code

(function (){
  $(function(){
  $("#keyWord").on("keyup",function(event){
    var keyCode = event.keyCode;
    if(keyCode == 38|| keyCode ==40){
      settingTipList(keyCode);
      return false;
    }
    var keyWord = $(this).val();
    getTipList(keyWord);
  });
  var index = -1;
  function settingTipList(keyCode){
    if(keyCode == 38){
      index--;
    }else{
      index++;
    }
    var size = $("#tipList li").size();
    index =index % size;
    $("#tipList li").removeClass("active").eq(index).addClass("active");
    var selectLiContent = $("#tipList li").eq(index).html();
    $("#keyWord").val(selectLiContent);
  };
  //获取数据
  function getTipList(keyWord){
    var url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su";
    var data = {
      wd:keyWord,
      cb:"hhh"
    };
    $.ajax({
      url:url,
      data:data,
      type:"GET",
      dataType:"jsonp",
      jsonpCallback:"hhh",
      success:function(data){
        var tipList = data.s;
        handleData(tipList)
      },
      error:function(error){
        alert("接口出错")
      }
    });
  }
  });
  function handleData(tipList){
    var tipHTML= "";
    for(var i in tipList){
      var text = tipList[i];
      tipHTML += "<li>"+text+"</li>"
    }
    $("#tipList").css({"opacity":"1"});
    $("#tipList").html(tipHTML);
  }
})()
//如果不写jsonpCallback、后面jsonpCallback“”空置、直接跳出“接口出错了。
Copy after login

Note:

1. Use ajax to make JSONP cross-domain request, because the callback function name of the requested party cannot be modified. There will be multiple different JSONP requests in this page, but their callback function names are all the same, _Callback. Think of setting the JSONP parameters of AJAX. But found it didn't work at all. Finally, I accidentally discovered that jsonpcallback is case-sensitive. Is jsonpCallback instead of jsonpcallback;

2. JSONP is a powerful technology for building mashups, but unfortunately, it is not a panacea for all cross-domain communication needs. It has some flaws, which must be carefully considered before committing resources to development. First, and most importantly, there is no error handling for JSONP calls. If the dynamic script insertion is valid, the call is executed; if it is invalid, it fails silently. There is no prompt for failure. For example, 404 errors cannot be caught from the server, and requests cannot be canceled or restarted. However, if there is no response after waiting for a while, ignore it. (Future versions of jQuery may have features to terminate JSONP requests) Another major drawback of JSONP is that it can be dangerous when used by untrusted services. Because the JSONP service returns a JSON response wrapped in a function call that is executed by the browser, it makes the host web application more vulnerable to a variety of attacks. If you plan to use JSONP services, it is important to understand the threats that can be posed.

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:

Detailed explanation of value transfer and slot application steps of vue parent-child components

VeeValidate form validation in vue project Test use case code analysis

The above is the detailed content of Detailed explanation of JavaScript callback function use cases. 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles