使用javascript发送特殊字符

send special characters with javascript

本文关键字:特殊字符 javascript 使用      更新时间:2023-09-26

i使用javascript和$_POST方法发送用户名。它使用简单的用户名,但使用具有特殊字符(如"Al[!]e$e")的用户名有问题,无法在我的数据库中找到用户名。

<div class="friend-add">
<form method="post" action="" class="form-inline">
<fieldset>
<input name="username" id="username" placeholder="Username" autocomplete="off" type="text">
<button id="add_friend" name="add_friend" type="submit" class="btn">Add friend</button>
</fieldset>
</form>
<div id="loading_m" style="position:relative; width:16px; height:16px; float:left; margin-top:-30px;margin-left:330px;background-image:url(loading.gif); background-repeat:no-repeat; background-size:16px 16px; display:none;"></div>
</div>

<script language="javascript" type="text/javascript">
$("#add_friend").click(function(){
$("#add_friend").attr("disabled","disabled");
$("#loading_m").fadeOut('fast');
$("#loading_m").fadeIn('fast');
$("#alert_m").html("");
$.post("friend_request.php", { friend_username : $("#username").val() })
    .done(function(data) {
        //alert(data);
        if (data.toLowerCase().indexOf("notexist") >= 0){
            $("#loading_m").fadeOut('fast',function(){
                $("#alert_m").html("<b style='color:#FF0040;'>This user does not exist.</b>").fadeIn('fast').delay(5000).fadeOut('fast');
                $("#add_friend").removeAttr('disabled');
            });
        }
        ......
                .fail(function(){
        $("#loading_m").fadeOut('fast',function(){
                $("#alert_m").html("<b style='color:#F00;'>Something wrong with server please try again later.</b>").fadeIn('fast').delay(5000).fadeOut('fast');
                $("#add_friend").removeAttr('disabled');
            });
     });
     return false;

});

为什么应该使用encodeURIComponent:什么时候应该使用escape而不是encodeURI/encodeURIComponent?

...
$.post("friend_request.php", { friend_username : encodeURIComponent($("#username").val()) })
...

编辑:使用php中的urldecode()将其转换回原始字符串。

$username = urldecode($_POST['friend_username']);

参考编号:http://www.php.net/manual/en/function.urldecode.php