(四)跨域请求

tips:允许跨域示例

{
    ...
    "permissions": [
        "*://*.wikipedia.org/*"
    ]
}

  1. 每次发起请求,只要调用httpRequest函数,并传入要请求的URL和接收返回结果的函数就可以了。
    为什么要使用callback函数接收请求结果,而不直接用return将结果作为函数值返回呢?
    因为XMLHttpRequest不会阻塞下面代码的运行。(异步)
function httpRequest(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            callback(xhr.responseText);
        }
    }
    xhr.send();
}
  1. 小项目 用户IP展示
    manifest
{
    "manifest_version": 2,
    "name": "查看我的IP",
    "version": "1.0",
    "description": "查看我的电脑当前的公网IP",
    "icons": {
        "16": "images/icon16.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "browser_action": {
        "default_icon": {
            "19": "images/icon19.png",
            "38": "images/icon38.png"
        },
        "default_title": "查看我的IP",
        "default_popup": "popup.html"
    },
    "permissions": [
        "http://user.ip138.com/ip/"
    ]
}

popu.html

<html>
<head>
<style>
* {
    margin: 0;
    padding: 0;
}

body {
    width: 400px;
    height: 100px;
}

div {
    line-height: 100px;
    font-size: 42px;
    text-align: center;
}
</style>
</head>
<body>
<div id="ip_div">正在查询……</div>
<script src="js/my_ip.js"></script>
</body>
</html>

my_ip.js

function httpRequest(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            callback(xhr.responseText);
        }
    }
    xhr.send();
}

httpRequest('http://user.ip138.com/ip/', function(ip){
    document.getElementById('ip_div').innerText = ip;
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值