Home > Web Front-end > JS Tutorial > body text

Detailed explanation of steps to use JS callback function

php中世界最好的语言
Release: 2018-05-31 09:36:50
Original
1920 people have browsed it

This time I bring you JS callbackCallback functionDetailed explanation of the steps to use, what are the notes when using the JS callback 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 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 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:

How to use vuex in combination with components

How to use vux-ui to customize form verification

The above is the detailed content of Detailed explanation of steps to use JS callback function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template