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
    es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

    去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

    JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

    原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

    怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

    JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

    javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

    方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

    JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

    foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

    foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

    整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.