How To Use JSONP Method To Create Dynamic Script Tag

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

JSONP is a method for sending JSON data without worrying about cross-domain issues.JSONP does not use the XMLHttpRequest object.JSONP uses the script tag instead. so today we are discuss how to create dynamic script tag

How To Use JSONP Method To Create Dynamic Script Tag

JSONP stands for JSON with Padding.

Requesting a file from another domain can cause problems, due to cross-domain policy.

Requesting an external script from another domain does not have this problem.

JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.
 

Creating a Dynamic Script Tag

Execute the "myFunc" function when the page is loading, based on where you put the script tag, which is not very satisfying.

The script tag should only be created when needed:

Let's Learn

Step 1:

Create Index.php file and implement code as below

<button class="btn btn-success" onclick="clickButton()">Click me!</button>

<h2 id="demo"></h2>


Step 2:
Create json_demo.php file and implement code as below.

<?php
$myJSON = '{ "name":"Shiva", "age":30, "city":"New York" }';

echo "myFunc(".$myJSON.");";
?>


Step 3:
Now we implement java script to get data from database from php file.

<script>
    function clickButton() {
        var s = document.createElement("script");
        s.src = "json_demo.php";
        document.body.appendChild(s);
    }

    function myFunc(myObj) {
        document.getElementById("demo").innerHTML = myObj.name;
    }
</script>


Complete Code For JSONP Method To Create Dynamic Script Tag

<!DOCTYPE html>
<html>
<head>
    <title>How To Use JSONP Method To Create Dynamic Script Tag</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How To Use JSONP Method To Create Dynamic Script Tag</h1>
    </div>
    <div class="well">
        <button class="btn btn-success" onclick="clickButton()">Click me!</button>


        <h2 id="demo"></h2>
    </div>

    <script>
        function clickButton() {
            var s = document.createElement("script");
            s.src = "json_demo.php";
            document.body.appendChild(s);
        }

        function myFunc(myObj) {
            document.getElementById("demo").innerHTML = myObj.name;
        }
    </script>
</div>
</body>
</html>

 

Related Post