首页 > 解决方案 > 验证时防止ajax中的&符号破坏?

问题描述

function authenticate(){

    var email = 'john.doe@gmail.com';
    var password = '123&567';

    var ajaxRequest;

    credentials = "cmd=login&email="+email+"&password="+password;

    var ajaxRequest = new XMLHttpRequest();
    ajaxRequest.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert(this.responseText);
        }
    };

    ajaxRequest.open('POST', 'http://xx', true);
    ajaxRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(credentials);

    return false;
}

调用函数后结果如下:

cmd=login&email="+"john.doe@gmail.com"+"&password="+"123&567";

标签: ajax

解决方案


您可以使用该功能encodeURIComponent对密码进行编码:

var email = 'john.doe@gmail.com';
var password = '123&567';

var ajaxRequest;

credentials = "cmd=login&email="+email+"&password="+encodeURIComponent(password);
console.log(credentials);
/* ... */

在你的 PHP 中,你可以使用urldecode它来解码它。


推荐阅读