简体   繁体   中英

Transfer Base64 from PHP to Javascript

First of all I'm new here and new in the programming business. :)

So my problem:

I have Base64 images witch are stored in a database. Now i am selecting the data with PHP but i need the Data in Javascript. Without the Base64 images it's no problem to transfer the data from PHP to Javascript with following Code:

PHP:

require "Controller.php"; $controller = new Controller; $data= $controller->getData();

Javascript:

var data = <?php echo json_encode($data); ?>

And now my question: How do i transfer base64 code from PHP to Javascript? Or is there another way to use the Images in javascript if they are in a MySQL Database ?

I hope someone can help me here. Thanks :D

This should do:

btoa(atob(data))

See btoa and atob .

Try with Ajax to run the request in your php file.

Your javascript code

<script>

function getBase64(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = this.responseText;
        }
    };
    xmlhttp.open("GET", "yourFile.php, true);
    xmlhttp.send();
}

</script>

Your yourFile.php code

<?php echo json_encode($data); ?>

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