简体   繁体   English

如何解决此错误:无法设置 null 的属性(设置“innerHTML”)

[英]How do I solve this error: Cannot set properties of null (setting 'innerHTML')

I recently live hosted my website and got this error.我最近现场托管了我的网站并收到此错误。 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at response (home:2593) at XMLHttpRequest.未捕获的类型错误:无法在 XMLHttpRequest 的响应 (home:2593) 中设置 null 的属性(设置“innerHTML”)。 (home:2560) (主页:2560)

This error did not occur on the local server but it occurred on a public server.这个错误没有发生在本地服务器上,而是发生在公共服务器上。 I saw a few threads regarding this error and I heard that you should use addEventListener instead of onclick in your code.我看到了一些关于此错误的线程,我听说您应该在代码中使用 addEventListener 而不是 onclick。 However, I'm not sure how to implement it into my code so it would be great if you could help me.但是,我不确定如何将它实现到我的代码中,因此如果您能帮助我,那就太好了。

This is the line where the error occurred:这是发生错误的行:

info_element.innerHTML = obj.info;

This is the JS:这是JS:

<script type="text/javascript">
        function ajax_send(data, element) {

            var ajax = new XMLHttpRequest();

            ajax.addEventListener('readystatechange', function() {

                if (ajax.readyState == 4 && ajax.status == 200) {

                    response(ajax.responseText, element);
                }

            });

            data = JSON.stringify(data);

            ajax.open("post", "<?= ROOT ?>ajax.php", true);
            ajax.send(data);

        }

        function response(result, element) {

            if (result != "") {

                var obj = JSON.parse(result);
                if (typeof obj.action != 'undefined') {

                    if (obj.action == 'like_post') {

                        var likes = "";

                        if (typeof obj.likes != 'undefined') {
                            likes =
                                (parseInt(obj.likes) > 0) ?
                                '<svg fill="#1877f2" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>' :
                                '<svg fill="#626a70cf" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>';
                            element.innerHTML = likes;
                        }

                        if (typeof obj.info != 'undefined') {
                            var info_element = document.getElementById(obj.id);
                            info_element.innerHTML = obj.info;
                        }
                    }
                }
            }
        }

        function like_post(e) {

            e.preventDefault();
            var link = e.currentTarget.href;

            var data = {};
            data.link = link;
            data.action = "like_post";
            ajax_send(data, e.currentTarget);
        }
    </script>

This is where I implemented like_post in my HTML:这是我在 HTML 中实现 like_post 的地方:

<a onclick="like_post(event)" href="<?= ROOT ?>like/post/<?php echo $ROW['postid'] ?>" style="text-decoration:none;float:left;position:relative;top:2px;">
                <svg id="icon_like" fill="<?= $Like_color ?>" width="22" height="22" viewBox="0 0 24 24">
                    <path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z" />
                </svg>
            </a>

I also did some debugging using console.log.我还使用 console.log 进行了一些调试。 This is what I received when I console.log(obj.id):这是我在 console.log(obj.id) 时收到的:

info_

It's supposed to return some values after info_ eg.143884它应该在 info_ eg.143884 之后返回一些值

This is the code in ajax.php:这是ajax.php中的代码:

<?php

include("classes/autoload.php");

$data = file_get_contents("php://input");
if($data != ""){
  $data = json_decode($data);
}

if(isset($data->action) && $data->action == "like_post"){

  include("ajax/like.ajax.php");
}

This is the code in like.ajax.php:这是like.ajax.php中的代码:

<?php

if(!empty($data->link)){
    $URL = split_url_from_string($data->link);
}

$_GET['type'] = isset($URL[5]) ? $URL[5] : null;
$_GET['id'] = isset($URL[6]) ? $URL[6] : null;


$_SESSION['mybook_userid'] = isset($_SESSION['mybook_userid']) ? $_SESSION['mybook_userid'] : 0;
$login = new Login;
$user_data = $login->check_login($_SESSION['mybook_userid'],false);

//check if not logged in
if($_SESSION['mybook_userid'] == 0){

        $obj = (object)[];
        $obj->action = "like_post";

        echo json_encode($obj);
        die;
}

/*
 $query_string = explode("?", $data->link);
 $query_string = end($query_string);

$str = explode("&", $query_string);

foreach ($str as $value) {
    # code...
    $value = explode("=", $value);
    $_GET[$value[0]] = $value[1];
}
*/

$_GET['id'] = addslashes($_GET['id']);
$_GET['type'] = addslashes($_GET['type']);

    if(isset($_GET['type']) && isset($_GET['id'])){

        $post = new Post();

        if(is_numeric($_GET['id'])){

            $allowed[] = 'post';
            $allowed[] = 'user';
            $allowed[] = 'comment';

            if(in_array($_GET['type'], $allowed)){


                $user_class = new User();
                $post->like_post($_GET['id'],$_GET['type'],$_SESSION['mybook_userid']);

                if($_GET['type'] == "user"){
                    $user_class->follow_user($_GET['id'],$_GET['type'],$_SESSION['mybook_userid']);

                }

            }

        }

        //read likes
        $likes = $post->get_likes($_GET['id'],$_GET['type']);

        //create info
        /////////////////
        $likes = array();
        $info = "";

                $i_liked = false;
                if(isset($_SESSION['mybook_userid'])){

                    $DB = new Database();

                    $sql = "select likes from likes where type='post' && contentid = '$_GET[id]' limit 1";
                    $result = $DB->read($sql);
                    if(is_array($result)){

                        $likes = json_decode($result[0]['likes'],true);

                        $user_ids = array_column($likes, "userid");

                        if(in_array($_SESSION['mybook_userid'], $user_ids)){
                            $i_liked = true;
                        }
                    }

                }

                $like_count = count($likes);

                if($like_count > 0){

                    $info .= "<br/>";

                    if($like_count == 1){

                        if($i_liked){
                            $info .= "<div style='text-align:left;'>You liked this post </div>";
                        }else{
                            $info .= "<div style='text-align:left;'> 1 person liked this post </div>";
                        }
                    }else{

                        if($i_liked){

                            $text = "others";
                            if($like_count - 1 == 1){
                                $text = "other";
                            }
                            $info .= "<div style='text-align:left;'> You and " . ($like_count - 1) . " $text liked this post </div>";
                        }else{
                            $info .= "<div style='text-align:left;'>" . $like_count . " others liked this post </div>";
                        }
                    }


                }

        /////////////////////////
        $obj = (object)[];
        $obj->likes = count($likes);
        $obj->action = "like_post";
        $obj->info = $info;
        $obj->id = "info_$_GET[id]";

        echo json_encode($obj);


    }

Probably it's related to a syntax error in your $_GET['id'] variable.可能与$_GET['id']变量中的语法错误有关。
That's why console.log(obj) returned an empty id.这就是console.log(obj)返回空 ID 的原因。

<?php echo $_GET[id]; // id is not enclosed by quotes ?>

Won't work on most servers running php7.x.不适用于大多数运行 php7.x 的服务器。
Make sure to always enclose your variable name in quotes (most of the time you did this, anyway).确保始终将变量名括在引号中(无论如何,大多数情况下都是这样做的)。

<?php echo $_GET['id']; ?>

To simplify escaping, save your $_GET['id'] to a variable and sanitize it before you pass it to a sql query.为了简化转义,将您的 $_GET['id'] 保存到一个变量并在将其传递给 sql 查询之前对其进行清理。
Try this:尝试这个:

Setting $_GET['id']设置 $_GET['id']
Replace null with '' – this way you save a lot of additional isset() checking eg用 '' 替换 null——这样你就可以节省很多额外的 isset() 检查,例如

$_GET['id'] = isset($URL[6]) ? $URL[6] : '';
$_GET['type'] = isset($URL[5]) ? $URL[5] : '';

Saving to a sanitized variable:保存到消毒变量:
You can now operate with this sanitized $_id variable instead of $_GET['id'].您现在可以使用这个经过消毒的 $_id 变量而不是 $_GET['id'] 进行操作。

$_id = $_GET['id'] ? htmlspecialchars( $_GET['id'], ENT_QUOTES) : '';
$_type = $_GET['type'] ? htmlspecialchars( $_GET['type'], ENT_QUOTES) : '';

Don't sanitize $_GET/$_POST (and other superglobals) variables by redefining them.不要通过重新定义$_GET/$_POST(和其他超全局变量)变量来清理它们。 Better leave them as the are but sanitize variables before any further usage (like echoeing, returning, passing to other functions etc.)最好保持原样,但在进一步使用之前清理变量(如回声、返回、传递给其他函数等)

See also this thread: Sanitizing user's data in GET by PHP另请参阅此线程: 通过 PHP 在 GET 中清理用户数据

DB query (the previous code also contained the enclosing issue): DB 查询(前面的代码也包含封闭问题):

$sql = "select likes from likes where type='post' && contentid = '$_id' limit 1";

Create your object data创建对象数据

$obj->id = 'info_'.$_id;

Code simplification and tweaks代码简化和调整
As our ids and type variables are always defined (but maybe empty), you can focus on checking the values.由于我们的 id 和类型变量总是被定义(但可能是空的),你可以专注于检查值。

if( $_id && $_type ){ }

instead of代替

if(isset($_GET['type']) && isset($_GET['id'])){

The 'allowed array' might also cause some php warnings (depending on your php version etc.) – since you add array items to an array that hasn't been defined before. “允许的数组”也可能会导致一些 php 警告(取决于您的 php 版本等)——因为您将数组项添加到之前尚未定义的数组中。 Better write it like this:最好这样写:

$allowed = array('post', 'user', 'comment');

JS part JS部分

if(info_element){
    info_element.innerHTML = obj.info
}

You should keep this condition as it just prevents the 'Cannot set properties of null' console.error.您应该保持此条件,因为它只会防止“无法设置 null 的属性”console.error。

The main problem should be solved by the aforementioned php fixes.主要问题应该通过上述 php 修复来解决。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决错误 =&gt;“无法设置 null 属性(设置&#39;innerHTML&#39;)”? - How do I solve error => "Cannot set properties of null (setting 'innerHTML')"? 为什么我得到 Cannot set properties of null (setting 'innerHTML') - Why do I get an Cannot set properties of null (setting 'innerHTML') 如何解决错误“无法设置 null 的属性‘innerHTML’” - How can I solve error "Cannot set property 'innerHTML' of null " 错误:未捕获类型错误:无法设置 null 的属性(设置“innerHTML”) - Error: Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') 无法设置 null 的属性(设置“innerHTML”) - Cannot set properties of null (setting 'innerHTML') 如何解决未捕获的类型错误:尝试使用 JS 和 html 显示当前时间时,无法在打印时间设置 null 的属性(设置“innerHTML”) - How to solve Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at printTime when trying to show current time with JS and html 语法中的innerHTML 错误不起作用; 未捕获的类型错误:无法设置 null 的属性(设置“innerHTML”) - innerHTML error in syntax not working; Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') 如何在反应中解决无法设置 null 的属性(设置“内部 HTML”)? - how to solve in react Cannot set properties of null (setting 'inner HTML')? 我如何解决此错误,无法在Ionic中将MyLocation设置为null - how do i solve this error cannot set MyLocation of null in ionic 未捕获(承诺中)类型错误:无法设置 null 的属性(设置“innerHTML”) - Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerHTML')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM