ajax technology-JSONP obtains the list of high-risk areas in the epidemic

1 <script>
2        var name = 'jsonp' + Math.random().toString().replace('.', '');//定义回调函数名
3        window[name] = function(data){//定义回调函数,将它挂载在全局对象下
4            console.log(typeof  data); //输出返回数据的数据类型
5            console.log(data);//输出获取的数据
6        };
7        var script = document.createElement('script'); //创建< script >标签
8        var attr = document.createAttribute('src');// 创建< src>属性
9        //设置其src属性为一个跨域的url,包含参数callback,其值为定义的回调函数名
10        attr.value = '服务器地址' + '?callback=' + name;
11        script.setAttributeNode(attr); //将src属性添加至< script >标签
12        document.body.appendChild(script); //将< script >标签添加至页面
13 </script>

In Example 10-4, the 2nd line of code declares a random callback function name; the 3-6 line of code defines the function of the callback function, where the parameter data is used to receive server data; the 7-11 line of code creates the < script > tag and Initialize its attribute value ; the code on line 12 adds the newly created < script > tag to the body , and the browser will obtain the JSON data from the set server address. 10-4 Output the effect in the Chrome browser console, as shown in Figure 10-9. Among them, the data attribute of the returned data is an array, and each item is a risk area object, area represents an area, the type value is 1 for a medium-risk area, and the value for 2 is a high-risk area.

 Figure 10-9 Partial screenshot of the running results of Example 10-4


Video explanation: ajax technology - access to real-time data of the global new crown epidemic_哔哩哔哩_bilibili

Source code: Tsinghua University Press-Book Details-"JavaScript front-end development and example tutorial (micro class video version)"

Guess you like

Origin blog.csdn.net/weixin_43396749/article/details/128019843