What are the differences between JSON and JSONP?

后端 未结 8 1823
感情败类
感情败类 2020-11-22 03:53

Format wise, file type wise and practical use wise?

相关标签:
8条回答
  • 2020-11-22 03:55

    JSON

    JSON (JavaScript Object Notation) is a convenient way to transport data between applications, especially when the destination is a JavaScript application.

    Example:

    Here is a minimal example that uses JSON as the transport for the server response. The client makes an Ajax request with the jQuery shorthand function $.getJSON. The server generates a hash, formats it as JSON and returns this to the client. The client formats this and puts it in a page element.

    Server:

    get '/json' do
     content_type :json
     content = { :response  => 'Sent via JSON',
                :timestamp => Time.now,
                :random    => rand(10000) }
     content.to_json
    end
    

    Client:

    var url = host_prefix + '/json';
    $.getJSON(url, function(json){
      $("#json-response").html(JSON.stringify(json, null, 2));
    });
    

    Output:

      {
       "response": "Sent via JSON",
       "timestamp": "2014-06-18 09:49:01 +0000",
       "random": 6074
      }
    

    JSONP (JSON with Padding)

    JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.

    The only change on the client side with JSONP is to add a callback parameter to the URL

    Server:

    get '/jsonp' do
     callback = params['callback']
     content_type :js
     content = { :response  => 'Sent via JSONP',
                :timestamp => Time.now,
                :random    => rand(10000) }
     "#{callback}(#{content.to_json})"
    end
    

    Client:

    var url = host_prefix + '/jsonp?callback=?';
    $.getJSON(url, function(jsonp){
      $("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
    });
    

    Output:

     {
      "response": "Sent via JSONP",
      "timestamp": "2014-06-18 09:50:15 +0000",
      "random": 364
    }
    
    0 讨论(0)
  • 2020-11-22 03:59

    JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

    //JSON
    {"name":"stackoverflow","id":5}
    //JSONP
    func({"name":"stackoverflow","id":5});
    

    The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

    function func(json){
      alert(json.name);
    }
    var elm = document.createElement("script");
    elm.setAttribute("type", "text/javascript");
    elm.src = "http://example.com/jsonp";
    document.body.appendChild(elm);
    
    0 讨论(0)
  • 2020-11-22 04:01

    “JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?

    Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.

    0 讨论(0)
  • 2020-11-22 04:12

    JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.

    jsonCallback(
    {
        "sites":
        [
            {
                "siteName": "JQUERY4U",
                "domainName": "http://www.jquery4u.com",
                "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
            },
            {
                "siteName": "BLOGOOLA",
                "domainName": "http://www.blogoola.com",
                "description": "Expose your blog to millions and increase your audience."
            },
            {
                "siteName": "PHPSCRIPTS4U",
                "domainName": "http://www.phpscripts4u.com",
                "description": "The Blog of Enthusiastic PHP Scripters"
            }
        ]
    });
    
    (function($) {
    var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';
    
    $.ajax({
       type: 'GET',
        url: url,
        async: false,
        jsonpCallback: 'jsonCallback',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(json) {
           console.dir(json.sites);
        },
        error: function(e) {
           console.log(e.message);
        }
    });
    
    })(jQuery);
    

    Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.

    0 讨论(0)
  • 2020-11-22 04:15

    JSONP allows you to specify a callback function that is passed your JSON object. This allows you to bypass the same origin policy and load JSON from an external server into the JavaScript on your webpage.

    0 讨论(0)
  • 2020-11-22 04:17

    Basically, you're not allowed to request JSON data from another domain via AJAX due to same-origin policy. AJAX allows you to fetch data after a page has already loaded, and then execute some code/call a function once it returns. We can't use AJAX but we are allowed to inject <script> tags into our own page and those are allowed to reference scripts hosted at other domains.

    Usually you would use this to include libraries from a CDN such as jQuery. However, we can abuse this and use it to fetch data instead! JSON is already valid JavaScript (for the most part), but we can't just return JSON in our script file, because we have no way of knowing when the script/data has finished loading and we have no way of accessing it unless it's assigned to a variable or passed to a function. So what we do instead is tell the web service to call a function on our behalf when it's ready.

    For example, we might request some data from a stock exchange API, and along with our usual API parameters, we give it a callback, like ?callback=callThisWhenReady. The web service then wraps the data with our function and returns it like this: callThisWhenReady({...data...}). Now as soon as the script loads, your browser will try to execute it (as normal), which in turns calls our arbitrary function and feeds us the data we wanted.

    It works much like a normal AJAX request except instead of calling an anonymous function, we have to use named functions.

    jQuery actually supports this seamlessly for you by creating a uniquely named function for you and passing that off, which will then in turn run the code you wanted.

    0 讨论(0)
提交回复
热议问题