最近在做一個報表的時候使用了ajax技術,將用戶在頁面操作之後,異步的結果利用js在特定的位置顯示,
比如xmlHttp.responseText返回的結果是 "123456,操作成功", 那麼我直接在用戶id 123456下方的一個span標籤裏面顯示操作結果 " 操作成功"
那麼首先就需要得到標籤id,再利用innerText就可以了
<span class="STYLE3" name = "alertuser" id="alert123456" color =red></span>
我的頁面更新js函數
function updatePage()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var response = xmlHttp.responseText;
var uid=response.split(','); //這時候uid[0]就是123456(如果response 爲 123456,操作成功 )uid[1]是”操作成功“
var which= 'alert'+uid[0]; //
alert(which);
$(which).innerText = uid[1];
}
}
response 的內容是"123456,操作成功"
按所想which的提示對話框彈出的內容就是alert123456
可是在瀏覽器裏裏面就是提示
谷歌:Uncaught TypeError: Cannot set property 'innerText' of null
IE: 對象爲NULL
於是google 百度 關鍵字 “ID存在
getElementById 爲空" 還是沒有找到我想要的答案
再去嘗試 如果修改成下面這種方式 就可以,但是不能再特定用戶位置顯示。
var which= 'alert123456';
alert(which);
上面的方式能夠成功得到對象 並且innerText
也成功,說明在responseText返回之後解析的用戶id的時候uid[0]有問題
那麼可以看一下which變量的長度
var uid=response.split(',');
var which= 'alert'+uid[0];
alert(which);
alert(which.length);
雖然彈出的對話框顯示的是‘alert123456’,但是彈出的長度卻是12,說明變量which裏面含有未知字符
通過用正則表達式
which=which.replace(/[^a-z0-9]/gi,'');
去除之後就可以正常在網頁特定位置顯示內容了。