ChatGPT解决这个技术问题 Extra ChatGPT

What are the differences between JSON and JSONP?

Format wise, file type wise and practical use wise?

Is one method faster than the other? For example, if you use XMLHttpRequest to GET a request (to the same domain obviously since it's 'normal' ajax), or if you use the JSONP method (which won't use the XMLHTTPRequest) - will one be faster than the other? I know it depends on several factors - but did someone do speed comparisons?

i
isherwood

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);

Is there still a point to JSONP assuming you can configure CORS to allow cross origin requests?
Maybe a bit late but however I want to give answer to your question for others, No, if you use the JSONP you dismissed the all CORS advantages (I called advantage becasue of the security issue.) I recommend you to implement CORS properly, This will help you about security issues and also better approach on architecture.
m
mpen

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.


Separate from what? JSON isn't a language either
@nickf: Yeah...I was looking for the right word... what would you call it then? "data-interchange format" according to json.org.
or more readable: JSON: a javascript object in "text notation". Like you would toString() a Java object perhaps?
FWIW: @SamVloeberghs - Its a bit misleading to say that the JSON represents a javascript object. It could be any data, from any language or database, that is representable as name-value pairs and arrays. And additional conventions are required to accurately round-trip any JS object - see JSON: Unsupported native data types. Notably, JS Date comes back at far end as a string. weblog.west-wind.com/posts/2014/jan/06/…
A
Alex Wayne

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.


W
Wahid Bitar

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 &amp; 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.


D
Delan Azabani

JSONP is essentially, JSON with extra code, like a function call wrapped around the data. It allows the data to be acted on during parsing.


B
Bhargav Rao

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
}

V
Vasiliy Faronov

“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.


C
Cyber5h13ld

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

But the practical implementation of the approach involves subtle differences that are often not explained clearly.

Here is a simple tutorial that shows JSON and JSONP side by side.

All the code is freely available at Github and a live version can be found at http://json-jsonp-tutorial.craic.com


that link is broken