在普通html页面中使用axios问题

我直接在html中引用了 从axios cdn上下载来的js文件 并在js文件尾部加入如下代码

var uuid, bmid, url;
bmid = 2//这里写部门id
url = 'http://192.168.1.106:1024/kffp'//分配服务器地址

uuid = localStorage.getItem("uuid");
console.log(typeof uuid);
if (typeof (uuid) == 'undefined' || typeof (uuid) == 'null' || typeof (uuid) == '' || uuid == null) {

    localStorage.setItem("uuid", randomString());
    this.uuid = localStorage.getItem("uuid");
}

axios.post(this.url, {
    uuid: this.uuid,
    bmid: this.bmid
})
    .then(function (response) {
        console.log(response.data);
        alert(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });
    
    

然后访问html页面这段代码执行没问题,后来我把这段代码用 function 包裹起来了 因为我需要从html页面传参进来 变成

function kffphs(cc) {
var uuid, bmid, url;
bmid = 2//这里写部门id
url = 'http://192.168.1.106:1024/kffp'//分配服务器地址

uuid = localStorage.getItem("uuid");
console.log(typeof uuid);
if (typeof (uuid) == 'undefined' || typeof (uuid) == 'null' || typeof (uuid) == '' || uuid == null) {

    localStorage.setItem("uuid", randomString());
    this.uuid = localStorage.getItem("uuid");
}

axios.post(this.url, {
    uuid: this.uuid,
    bmid: this.bmid
})
    .then(function (response) {
        console.log(response.data);
        alert(JSON.stringify(response.data));
    })
    .catch(function (error) {
        console.log(error);
    });

};

变成这样了 然后html调用 kffphs(cc);报错 TypeError: Cannot read property 'protocol' of undefined 跟踪是在 console.log(error); 这行了 是哪里写错了

阅读 13.2k
1 个回答

你上面的url、uuid、bmid都是在window上下文声明的 所以没有函数作用域可以直接this调 但是下面你用function包了一层就不能用this了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题