jQuery Cross Domain Ajax(jsonp)

Perform a cross domain request
$.ajax({
  url: "http://www.pureexample.com/backend/ajax_crossdomain.aspx",
  dataType: 'jsonp',  //use jsonp data type in order to perform cross domain ajax
  crossDomain: true,
  data: data,
  success: callback,
  error: callback
});

jQuery cross domain ajax sends a variable 'callback', you need to take this variable along with your output
data to form a result like
jQuery17208137074627447873_1354083003424('{"Manufacturer":"BMW"}')

Backend script (ajax_crossdomain.aspx)
void DoJsonp()
{        
    //output json
    //[{
    //    "Manufacturer": "HUMMER",
    //    "Sold": 120,
    //    "Month": "2012-11"
    //}]

    StringBuilder sbJson = new StringBuilder();
    sbJson.Append("[{")
          .Append("    \"Manufacturer\": \"HUMMER\",")
          .Append("    \"Sold\": 120,")
          .Append("    \"Month\": \"2012-11\"")
          .Append("}]");

    Page.Controls.Clear();
    string callback = Request["callback"];

    //in backend script you need to form output result to something like this 
    //jQuery17208137074627447873_1354083003424('your data output')

    Response.Write(callback   "('"   sbJson.ToString()   "')");
}
ExampleCross domain ajax with jsonp
Source Code Expand
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Javascript -->
<script type="text/javascript">
$(document).ready(function (){
    $("#btn392").click(function(){                
        var url = "http://www.pureexample.com/backend/ajax_crossdomain.aspx";
        
        var success = function(data){
            var html = [];
            /* parse JSON */
            data = $.parseJSON(data);
            /* loop through array */
            $.each(data, function(index, d){            
                html.push("Manufacturer : ", d.Manufacturer, ", ",
                          "Sold : ", d.Sold, ", ", 
                          "Month : ", d.Month, "<br>");
            });

            $("#div391").html(html.join('')).css("background-color", "orange");
        };
        
        $.ajax({
          type: 'GET',    
          url: url,
          data:{todo:"jsonp"},
          dataType: "jsonp",
          crossDomain: true,          
          cache:false, 
          success: success,
          error:function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
          }
        });
    });
});
</script>

<!-- HTML -->
<a name="#jsonp-ajax"></a>
<div id="example-section39">    
    <div>Car sale report</div>
    <div id="div391"></div>
    <button id="btn392" type="button">Click </button>
</div>



comments powered by Disqus