尝试从 javascript 获取数据然后将其显示在 HTML 中时出错
2015-09-03
80
嗨,我从 url 获取数据,然后将其存储到变量中,然后使用 document.getElementById().innerHTML 在 html 中显示数据,但不知何故我一直收到此错误
“[错误] TypeError:null 不是对象(评估‘document.getElementById("firstname").innerHTML = fname') 全局代码”
谢谢
<script type="text/javascript">
var fname = ""
var lname = ""
var user = ""
var pass = ""
var email = ""
var con = ""
var group = ""
var uri_dec = ""
var uri_dec1 = ""
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
fname = $.urlParam('fname');
lname = $.urlParam('lname');
user = $.urlParam('user');
email = $.urlParam('email');
con = $.urlParam('con');
group = $.urlParam('group');
uri_dec = decodeURIComponent(con);
uri_dec1 = decodeURIComponent(group);
console.log($.urlParam('fname'));
console.log($.urlParam('lname'));
console.log($.urlParam('user'));
console.log($.urlParam('email'));
console.log($.urlParam('con'));
console.log($.urlParam('group'));
document.getElementById("firstname").innerHTML = fname
document.getElementById("lastname").innerHTML = lname;
document.getElementById("username").innerHTML = user
document.getElementById("email").innerHTML = email
document.getElementById("country").innerHTML = uri_dec
document.getElementById("group").innerHTML = uri_dec1
</script>
<p align="center" id="firstname"></p>
<p align="center" id="lastname" class="lastname"></p>
<p align="center" id="username" class="username"></p>
<p align="center" id="email" class="email"></p>
<p align="center" id="country" class="contry"></p>
<p align="center" id="group" class="group"></p>
2个回答
尝试将
innerHTML
更改为
innerText
。
Lucas Souza
2015-09-03
正如@SciFiThief 提到的,您的脚本在 html 加载之前执行。您需要在 html 标签之前包含脚本,或者使用“文档就绪”函数在 html 加载后执行脚本。
//Using Jquery
$(document).ready(function(){
//your script here
});
//Using vanilla Javascript
document.addEventListener("DOMContentLoaded", function(event) {
//your script here
});
Deftwun
2015-09-03