斯堪的纳维亚人物åäö在AJAX聊天框中消失

时间:2016-08-11 15:25:24

标签: javascript php jquery utf-8 character-encoding

Chatbox jQuery

$(document).ready(function() {

    // load messages every 1000 milliseconds from server.
    load_data = {'fetch':1};
    window.setInterval(function(){
     $.post('shout.php', load_data,  function(data) {
        $('.message_box').html(data);
        var scrolltoh = $('.message_box')[0].scrollHeight;
        $('.message_box').scrollTop(scrolltoh);
     });
    }, 1000);

    //method to trigger when user hits enter key
    $("#shout_message").keypress(function(evt) {
        if(evt.which == 13) {
                var iusername = $('#shout_username').val();
                var imessage = $('#shout_message').val();
                post_data = {'username':iusername, 'message':imessage};

                //send data to "shout.php" using jQuery $.post()
                $.post('shout.php', post_data, function(data) {

                    //append data into messagebox with jQuery fade effect!
                    $(data).hide().appendTo('.message_box').fadeIn();

                    //keep scrolled to bottom of chat!
                    var scrolltoh = $('.message_box')[0].scrollHeight;
                    $('.message_box').scrollTop(scrolltoh);

                    //reset value of message box
                    $('#shout_message').val('');

                }).fail(function(err) { 

                //alert HTTP server error
                alert(err.statusText); 
                });
            }
    });

    //toggle hide/show shout box
    $(".header").click(function (e) {
        //get CSS display state of .toggle_chat element
        var toggleState = $('.toggle_chat').css('display');

        //toggle show/hide chat box
        $('.toggle_chat').slideToggle();

        //use toggleState var to change close/open icon image
        if(toggleState == 'block')
        {
            $(".header div").attr('class', 'open_btn');
        }else{
            $(".header div").attr('class', 'close_btn');
        }


    });
});

如果我写:
消息:这将起作用,但ö或ädoe不是

控制台输出:

  

(X-请求-随着:XMLHttpRequest的)
  消息:此+意愿+工作+ +但%C3%A5 +或+%C3%A4 +能源部的+未

如何更改斯堪的纳维亚字符以匹配html替代品,例如& ouml;用户发送消息后在聊天框中的ö(我不希望用户在输入框中看到转换)?

或者是否有一些简单的方法来转换我的PHP脚本中那些%C3%A5格式的“字符”?

1 个答案:

答案 0 :(得分:1)

我不确定你的错误究竟在哪里,但是控制台输出看起来像是受欢迎的。因此,您可以在发送之前和收到消息之后尝试编码和解码消息,如下所示:

JS:

var encodedMessage = encodeURI(message); // takes "ö" and gives "%C3%B6"

var message = decodeURI(encodedMessage); // takes "%C3%B6" and gives "ö"

PHP(如果需要):urlencodeurldecode