mb_strlen() & strlen() don't return correct values from an Ajax call to PHP

前端 未结 2 1488
深忆病人
深忆病人 2021-01-14 02:17

How can I add a check in the PHP for the length of the $username passed. The site is UTF-8 but I believe Javascript is using a different encoding. You can see in the comm

2条回答
  •  清酒与你
    2021-01-14 03:01

    From a quick glance, you can clean this up:

    if (request.status == 200) {
        if (request.responseText == "available") {
            document.getElementById("txt_username").innerHTML = "NAME AVAILABLE!";
            document.images['img_username'].src=img_smile;
            document.getElementById("continue").disabled = false;
            document.getElementById("field_username").className = 'validated';
        } else if (request.responseText == "taken") {
            document.getElementById("txt_username").innerHTML = "NAME TAKEN!";
            document.images['img_username'].src=img_sad;
            document.getElementById("field_username").className = 'error';
        } else if (request.responseText == "invalid_too_short") {
            document.getElementById("txt_username").innerHTML = "TOO SHORT!";
            document.images['img_username'].src=img_sad;
            document.getElementById("field_username").className = 'error';
        } else {
            document.getElementById("txt_username").innerHTML = "AJAX ERROR!";
                    document.images['img_username'].src=img_sad;
            document.getElementById("field_username").className = 'error';
        }
      }
    

    to:

    // I prefer triple equals
    // Read more at http://javascript.crockford.com/style2.html
    if (request.status === 200) {
            // use variables!
            var txtUsername = document.getElementById('txt_username');
            var fieldUsername = document.getElementById('field_username');
            var imgUsername = document.getElementById('img_username');
    
            var response = request.responseText;
    
            var error = true;
    
            // you can do a switch statement here too, if you prefer
            if (response === "available") {
                txtUsername.innerHTML = "NAME AVAILABLE!";
    
                document.getElementById("continue").disabled = false;
    
                error = false;
    
            } else if (response === "taken") {
                txtUsername.innerHTML = "NAME TAKEN!";
    
            } else if (response === "invalid_too_short") {
                txtUsername.innerHTML = "TOO SHORT!";
    
            } else {
                txtUsername.innerHTML = "AJAX ERROR!";
            }
    
            // refactor error actions
            if (error) {
                imgUsername.src = img_sad;
                fieldUsername.className = 'error';
            } else {
                imgUsername.src = img_smile;
                fieldUsername.className = 'validated';
            }
    }
    

提交回复
热议问题