search
HomeWeb Front-endJS TutorialUse of JS callback function (with code)

This time I will bring you the use of JS callbackcallback function (with code), what are the precautions when using JS callback callback function, the following is a practical case, let’s take a look 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 to 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>
  </p><p>
    <input>
    </p>

    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 += "
  • "+text+"
  • "     }     $("#tipList").css({"opacity":"1"});     $("#tipList").html(tipHTML);   } })() //如果不写jsonpCallback、后面jsonpCallback“”空置、直接跳出“接口出错了。

    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:

    How to use vue to implement the 2048 mini game

    How to use vee-validate in Vue

    The above is the detailed content of Use of JS callback function (with code). 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's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

    JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

    JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

    JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

    Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

    Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

    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.

    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

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools