简体   繁体   中英

PHP base64 encoded response does not get decoded correctly in Javascript

Good day! I wonder why I cannot decode base64 response in javascript using atob or btoa or custom formulas like $.base64.decode().

This is what I have in php

$res = "Это тескт";
echo base64_decode($res);

This is what I have in jquery

$.ajax({
type: "GET",
url: "request.php",
success: function(data){
$('#elementid').html($.base64.decode(data));
//or $('#elementid').html(atob(data)); // it gives the same result as the above one.

On the page I see the following

ЭÑо ÑеÑкÑ

Base64 encoded data looks the following way

0K3RgtC+INGC0LXRgdC60YI=

If I try to decode using different web tools from BASE64 to UTF-8 I see correct result, but not on my page using the above functions. Please suggest.

UPDATE: @logic-unit thanks for the suggestion. I forgot to mention that the resulting page index.php has the following in the heading

<?php
header('Content-Type: text/html; charset=utf-8');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
...
</head>

I found an answer to the question. It seems that atob and btoa badly handle UTF-8 encoding.

It is described in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding Solution 2 from section The "Unicode Problem" worked well for me.

Solution #2 – rewriting atob() and btoa() using TypedArrays and UTF-8

Sounds like a character encoding issue on your page.

Make sure you have the correct encoding type specified in a meta tag in your HTML head.

http://www.w3.org/International/questions/qa-html-encoding-declarations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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