首页 > 解决方案 > 错误:[object HTMLParagraphElement],当从函数中分配变量时

问题描述

我有一个函数可以显示文件是否存在,如果存在,如果文件不存在,他将返回我的文件路径,他仍然会给我路径,以便他可以创建文件:

function getnamechats($user1,$user2){
   
    $filename1="chats/chat".$user1."&".$user2.".json";
         $filename2="chats/chat".$user2."&".$user1.".json";
    if (file_exists($filename1)) {
        return $filename1;
    }
    else if (file_exists($filename2)) {
        return $filename2;
    }
    else{ return $filename1;}
}

它可以很好地创建/打开要在其上写入的文件,我已经测试了很多次,并且我的 json 文件每次都会更新:

function send_chat($nick,$chat){
    global $userid;global $chatparse;
   $heasda=getnamechats($userid,$chatparse);
 $ok=$heasda;
    // read/write
    $filename = "$heasda";
    $fopen = fopen($filename,"r");
    $fgets = fgets($fopen);
    fclose($fopen);
    $decode = json_decode($fgets,true);
    // limit 10
    end($decode);
    if(key($decode) >= 10){
        array_shift($decode);
        $new_key =10;
    }
    else{
        $new_key = key($decode);
        $new_key++;}
    
    $format = array($nick,$chat);
    $decode[$new_key] = $format;
    $encode = json_encode($decode);
    // write
    $fopen_w = fopen($filename,"w");
    fwrite($fopen_w,$encode);
    fclose($fopen_w);
    
}

但是在打开/创建它以读取的函数中,我得到以下错误第一个变量是正确的(1),但第二个变量(假设在 & 之后)不起作用,并且出现错误 HTMLParagraphElement,例如:

聊天/聊天1&[对象 HTMLParagraphElement].json

然后,一旦触发了新的 msg,我就会再次调用 getnamechats() 函数,以检查文件是否仍然存在,如果存在,它会将变量 $heasda 发送给 show_chat($heasda) ,基本上它会执行与 send_chat 相同,但不是在上面写,而是读取它:

function show_chat($heasda){
   print_r($heasda);
    $filename = $heasda;
    $fopen = fopen($filename,"r");
    $fgets = fgets($fopen);
    fclose($fopen);
    $decode = json_decode($fgets,true);
    $val .= "<table  id='table' class=\"table table-condensed\">";
    foreach($decode as $post){
        
        $val .= "<tr><td><b style=\"color:#{$post[0]}\">{$post[0]}</b>: {$post[1]}</td></tr>";}
    
    $val .= "</table>";
    return $val;
}

if(isset($_POST["chat"]) && $_POST["chat"] != ""){
    $nick = $_SESSION['iduser'];
    $chat = $_POST["chat"];
    send_chat($nick,$chat); 
}

if(isset($_GET["chat"]) && $_GET["chat"] != ""){
    global $userid;global $chatparse;
   $heasda=getnamechats($userid,$chatparse);
    echo show_chat($heasda);
    exit;
}

?>

正如有人说它也可以是 JavaScript 继承代码,我读过它,但我仍然不能正确理解:

function autoloadpage() {
        $.ajax({
            url: "?chat=1&chat-pars="+secnum,
            type: "POST",
            success: function(data) {
                $("div#chat").html(data);
            }
        });
    }

标签: javascriptphp

解决方案


secnum是一个 DOM 元素,而不是其中的文本。您需要获取文本。

您还应该调用encodeURIComponent它以防它包含在 URL 中具有特殊含义的字符。

function autoloadpage() {
    $.ajax({
        url: "?chat=1&chat-pars="+encodeURIComponent(secnum.innerText),
        type: "POST",
        success: function(data) {
            $("div#chat").html(data);
        }
    });
}

推荐阅读