Kcko
11/1/2019 - 3:12 PM

Jsonp, json, js to html from another domain

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
</head>
<body>

    <!-- https://www.sitepoint.com/jsonp-examples/ -->

    <div style="background: goldenrod; padding: 1rem;">
        <script src="http://lab.rjwebdesign.cz/jsonp/js.php"></script>
    </div>

    <div style="background: burlywood; padding: 1rem;" id="jsonp">
    
    </div>
    <script>
   
        // 1 zpusob
        $.getJSON('http://lab.rjwebdesign.cz/jsonp/jsonp.php?callback=?', function(json){
            console.log(json);
        });

        // 2 zpusob
        function logResults(json) {
            console.log(json);
        }

        $.ajax({
        url: "http://lab.rjwebdesign.cz/jsonp/jsonp.php",
        dataType: "jsonp",
        jsonpCallback: "logResults"
        });
    </script>

</body>
</html>
<?php 

    header('Content-Type: text/html; charset=utf-8'); 

    function replace_newline($string) {
    return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
    }


    $html = array('user' => 'Kcko', 'position' => 'developer');

    $html = json_encode($html);
    echo $_GET['callback'] . '(' .$html . ');';







<?php 

header("content-type: application/x-javascript"); 


$html = 'user is Kcko , job: developer';
$html = replace_newline($html);
$html = str_replace("'", "\"", $html);


function replace_newline($string) {
    return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}

?>

document.write('<?= $html ?>');





<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

# Header add Access-Control-Allow-Origin "http://my-domain.com"