Uncaught TypeError: Cannot read property 'value'' of null

在用JS实现ajax做网页聊天室的时候,报了一个错误:

Uncaught TypeError: Cannot read property 'value'' of null
at chat (Glutinous_ Rice Balls.js:2)
at HTMLButtonElement .onclick ((index):60)

在这里插入图片描述
在这里插入图片描述

先来看一下前端JS代码:

function chat() {
    var text = document.getElementById("#text").valueOf();
    console.log(text);

    var xmlhttp = createXMLHttpRequest();

    xmlhttp.open("POST","/webpage/Control/",true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

    xmlhttp.send("text="+text);

    xmlhttp.onreadystatechange = function () {
        alert(xmlhttp.readyState);
        if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
            var temp = xmlhttp.responseText;

            alert(temp)
        }
    }
}

function createXMLHttpRequest() {
    var xmlHttp;
    try{
        xmlHttp = new XMLHttpRequest(); // 适用于大多数浏览器,以及IE7和IE更高版本
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");  // 适用于IE6
        } catch (e) {
            try{
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   // 适用于IE5.5,以及IE更早版本
            } catch (e){}
        }
    }
    return xmlHttp;
}

看其字面意思好像是说不能读取value这个属性,然后就发现,是我JS的ID选择器写错了,getElementById的双引号里边直接写id就可以了,不需要加#。

原文地址:https://www.cnblogs.com/AlexKing007/p/12338120.html