What are the differences between JSON and JSONP?

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

Format wise, file type wise and practical use wise?

8条回答
  •  梦毁少年i
    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.

提交回复
热议问题