jQuery Cross Domain Ajax(jsonp) example - Pure Example

jQuery Cross Domain Ajax(jsonp)

Perform a cross domain request
  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

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

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

    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 (){
        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");
          type: 'GET',    
          url: url,
          dataType: "jsonp",
          crossDomain: true,          
          success: success,
          error:function(jqXHR, textStatus, errorThrown){

<!-- 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>

comments powered by Disqus