RSS

How to do a AJAX JSONP (Cross Site Domain request)

10 Jun

PHP file

<?php
				header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
				header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
				header("Cache-Control: no-cache, must-revalidate" );
				header("Pragma: no-cache" );
				header("Content-type: application/json");
    if(isset($_GET['name']) && isset($_GET['callback']))
    {
        $obj->name = $_GET['name'];
        $obj->message = "Hello " . $obj->name;
        echo $_GET['callback']. '(' . json_encode($obj) . ');';
    }
?>
Javascript :
        $("#useJSONP").click(function(){
            $.ajax({
                url: 'http://domain.com/jsonp-demo.php',
                data: {name: 'xerxis'},
                dataType: 'jsonp',
                jsonp: 'callback',
                jsonpCallback: 'jsonpCallback',
                success: function(){
                    alert("success");
                }
            });
        });
    });
    function jsonpCallback(data){
        $('#jsonpResult').text(data.message);
         }
About these ads
 
Leave a comment

Posted by on June 10, 2011 in Javascript

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.