简体   繁体   English

来自PHP变量的javascript中的值不正确

[英]Incorrect value in javascript from PHP variable

I just want to start by saying I am not a JavaScript developer, I am new to this. 我只想开始说我不是JavaScript开发人员,对此我是陌生的。

Ok, so, I have a session value called id, this is a long (example: 76561198237133252) and I am passing this as a argument for a method. 好的,所以,我有一个名为id的会话值,这是一个很长的值(例如:76561198237133252),我将其作为方法的参数传递。 The issue is the id is not correct when the function is actually ran. 问题是当函数实际运行时,id不正确。

JS: JS:

function sendMessage(id) 
{
    var message = $("#message").val();
    if (message)
    {
        $.ajax(
        {
            url: 'addChatMessage.php', 
            type: 'POST', 
            data: '&id=' + id+ '&message=' + message, 
            dataType: 'text', 
            success: function (data) 
            {
                $('#chatMessages').load(document.URL +  ' #chatMessages');
                document.getElementById('message').value = '';
                $('#chatScrollable').animate({scrollTop:$(document).height()}, 1000);

                window.alert("Id: " + id);
            }
        });
    }
}

Html: HTML:

<div class="chat-input">
    <div class="input-group">
        <input type="text" id="message" class="form-control" placeholder="Message..." required>
        <!-- <input type="hidden" id="id" value="<?php //echo $_SESSION['id']; ?>"> -->
            <span class="input-group-btn">
                <button class="btn btn-default" id="msgButton" type="button" onclick="sendMessage(<?php echo $_SESSION['id']; ?>);">Send</button>
            </span>
        </div>
    </div>

Any help is appreciated. 任何帮助表示赞赏。

Use json_encode() in PHP to convert a PHP value to the corresponding Javascript literal. 在PHP中使用json_encode()将PHP值转换为相应的Javascript文字。 It will encode it properly to keep the same data type (eg putting quotes around a string). 它将正确编码以保持相同的数据类型(例如,在字符串两边加上引号)。

<button class="btn btn-default" id="msgButton" type="button" onclick="sendMessage(<?php echo htmlentities(json_encode($_SESSION['id'])); ?>);">Send</button>

You also need to use htmlentities() to convert the quotes around the string to entities. 您还需要使用htmlentities()将字符串周围的引号转换为实体。 Otherwise, the quote will match the quote after onclick= , and end the attribute. 否则,引号将与onclick=之后的引号匹配,并结束属性。

Javascript is both awesome and aggravating for this one reason: it auto-converts strings and numbers to make sense of impossible statements. 出于这一原因,JavaScript既出色又令人讨厌:它会自动转换字符串和数字,以使不可能的语句变得有意义。 Your id is a number, so it might not be converting to a string properly. 您的ID是一个数字,因此它可能无法正确转换为字符串。 Use the .toString() of id to fix this problem. 使用id的.toString()可以解决此问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM