php 我想访问特定Javascript函数外的局部变量[已关闭]

gcuhipw9  于 2022-11-21  发布在  PHP
关注(0)|答案(1)|浏览(166)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
2天前关闭。
Improve this question
我正在设计一个Whatsapp聊天应用程序,其中我有发送者和接收者之间的WA企业帐户和最终用户的实时消息。我希望本地php变量出现在一个函数内,可以访问其功能范围之外。让我知道一个解决方案,在最早的。下面提到的代码。

$chatId=$phonenumber."@c.us";
$curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.ultramsg.com/instance21130/chats/messages?token=qa2tyt1vec6sl8ss&chatId='.$chatId.'&limit=1000',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
    ));
    
    $response = curl_exec($curl);
    curl_close($curl);
    //echo $response;
    $jsoned = json_decode($response, true);
    //$sender_no = $_SESSION['mobile_number'];
    //echo $sender_no;
    foreach($jsoned as $messagetest){
        if($messagetest['fromMe']==false)
        {
            $isttimestamp = date("Y-m-d H:i:s", substr($messagetest['timestamp'], 0, 10));
            $recievermessage = $messagetest['body'];
            $recievermessagenumber = $messagetest['from'];
    $numbers = preg_replace('/[^0-9]/', '', $recievermessagenumber);
    $letters = preg_replace('/[^a-zA-Z]/', '', $recievermessagenumber);
    }
    }
    
    global $db;
    $query2 = "INSERT INTO users (username, email, user_type, number, password) 
                              VALUES('Test User', 'test', 'user', '$numbers', 'test')";
                    mysqli_query($db, $query2);
                    $_SESSION['success']  = "New user successfully created!!";
                $query = "INSERT INTO message (sender, recvId, body, phonenumber, status, recvIsGroup)
                              VALUES('$recvId', '$sender', '$recievermessage', '$phonenumber',  '$status' , '$recvIsGroup')";
                              mysqli_query($db, $query);
    $data = file_get_contents("php://input");
    echo "<pre>";
    print_r($data,1);
    echo "</pre>";
    $event = json_decode($data, true);
    if(isset($event)){
        //Here, you now have event and can process them how you like e.g Add to the database or generate a response
        $file = 'log.txt';  
        $data =json_encode($event)."\n";  
        $from = $event['data']['from'];
        $msg = $event['data']['body'];
        //send_msg($from,$msg);
        file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
    }   
        function sendMessage()
        {
            $msg = $_POST['msg'];       
                
            $id = 0;
            $sender      = $msg['sender'];
            $recvId      = $msg['recvId'];
            $body        = $msg['body'];
            $status      = $msg['status'];
            global $db;
            $new_exists = false;        
            $query = "SELECT * FROM users WHERE id=$recvId";
            $result = mysqli_query($db, $query) or die (mysqli_error($db));
            $object = mysqli_fetch_assoc($result);
            $phonenumber = empty($object) ? 0 : $object['number']; 
            $querytest = "SELECT * FROM users WHERE id=$sender";
            $resulttest = mysqli_query($db, $querytest) or die (mysqli_error($db));
            $objecttest = mysqli_fetch_assoc($resulttest);
            $phonenumbertest = empty($objecttest) ? 0 : $objecttest['number']; 
            $temp= explode('.',$body);
      $extension = end($temp);
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.ultramsg.com/instance21130/messages/chat",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_SSL_VERIFYHOST => 0,
      CURLOPT_SSL_VERIFYPEER => 0,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "token=qa2tyt1vec6sl8ss&to=$phonenumber&body=$body&priority=5&referenceId=",
      CURLOPT_HTTPHEADER => array(
        "content-type: application/x-www-form-urlencoded"
      ),
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
    //  echo $response;
    }
            $recvIsGroup = 0;
                                    
            if ($id == 0)
            {           
                global $db;
                $query = "INSERT INTO message (sender, recvId, body, phonenumber, status, recvIsGroup)
                              VALUES('$sender', '$recvId', '$body', '$phonenumbertest', '$status' , '$recvIsGroup')";
                mysqli_query($db, $query);
    
                // get last id of the created message
                $messageLastId = mysqli_insert_id($db);     
                
                $message = returnLastMessage($messageLastId);
                $arr['id']          = (int) $message['id'];
                $arr['sender']      = (int) $message['sender'];
                $arr['recvId']      = (int) $message['recvId'];     
                $arr['status']      = (int) $message['status'];
                $arr['recvIsGroup'] = false;
                $arr['time']        = $message['time'];
            }
            header('Content-Type: application/json');
            echo json_encode($arr);
            
            
        }

/** Code inside script.js **/

let sendMessage = () => {
    let value = DOM.messageInput.value;
    DOM.messageInput.value = "";
    if (value === "") return;

    let msg = {
        sender: user.id,
        body: value,
        time: mDate().toString(),
        status: 1,
        recvId: chat.isGroup ? chat.group.id : chat.contact.id,
        recvIsGroup: chat.isGroup
    };
    
    $.ajax({
        type: 'POST',       
        url: '../functions.php?action=sendMessage',
        cache: false,
        dataType: 'json',
        data: {msg},
        success: function(data) {
            addMessageToMessageArea(msg);
            MessageUtils.addMessage(msg);
            generateChatList();
        }
    });
};

我无法获取特定函数之外的本地变量...有什么快速的解决方案吗?

wlp8pajw

wlp8pajw1#

我有一个来自python的想法,如果它有帮助的话:与其尝试设置全局变量,不如创建一个类,将这些变量作为属性示例化一个对象,这些属性可以在使用它们的函数之外访问。这个想法来自于“QuantifiedCode”编写的“Python反模式”一书。
我对Javascript不太熟悉,所以这可能对你一点帮助都没有,但希望它至少能给你带来一个想法。祝你好运!

相关问题