JSONP是什么

JSONP代表“带填充的JSON”。JSONP是一种跨源传递Javascript表达式的方法;可以让网页从别的域名(网站)那获取资料,即跨域读取数据。它是一种获取数据的替代方法,可以绕过普通的AJAX调用无法绕过同源策略。

JSONP允许我们快速跨域使用API,但缺点是无法在旧版浏览器中执行错误检查;它也不允许我们发出POST请求。只有在浏览器中使用Javascript评估接收数据而产生的跨域调用才需要JSONP;实现CORS的接口不需要JSONP。例如,Twitter API和Google Maps API不需要JSONP。

JSONP的另一个缺点是它使您的应用程序容易受到您请求的外来源的XSS攻击。如果JSONP源的远程端不受信任,则您的应用程序将对XSS攻击开放。

JSON和JSONP之间的区别:

JSON: JavaScript使用JSON(JavaScript Object Notation)通过网络交换数据。它仔细查看JSON数据,它只是一个字符串格式的JavaScript对象。

例:

{"name":"zww", "id":1, "articlesWritten":5}

JSONP: JSONP是带填充的JSON。这里,填充意味着在返回请求之前将函数包装在JSON周围。

例:

HzwwFunction({"name":"zww", "id":1, "articlesWritten":5});

使用JSONP的方法:

● 在HTML代码中,包含脚本标记。此脚本标记的来源将是要从中检索数据的URL。Web服务允许指定回调函数。在URL中包含最后的回调参数。

● 当浏览器遇到script元素时,它会向源URL发送HTTP请求。

● 服务器通过函数调用中包含的JSON发送回响应。

● JSON响应采用字符串形式,由浏览器解析并转换为JavaScript对象。调用回调函数,并将生成的对象传递给它。

示例1:

<!DOCTYPE html> 
<html> 
<body> 
    <p id="paragraphElement"></p> 
  
    <!-- The server returns a call to the callback function 
    (processData) that will handle the JSON data -->
    <script> 
        function processData(myObj) { 
        console.log(myObj); 
        var para= document.getElementById("paragraphElement"); 
        for(var i=0; i<myObj.resultCount; i++){ 
            para.innerHTML= para.innerHTML + myObj.results[i].trackName 
                            + "<br>" ;  
            }  
        } 
    </script> 
      
<!-- Calling the iTunes API to search for Jack Johnson's songs and return  
        the first five items -->
    <script src="https://itunes.apple.com/search?term=jack+johnson&limit=5
    &callback=processData"></script> 
</body> 
</html>

输出:

Better Together
Banana Pancakes
Sitting, Waiting, Wishing
Upside Down
Good People

示例2:使用JavaScript动态添加脚本元素

<!DOCTYPE html> 
<html> 
<body> 
    <p id="paragraphElement"></p> 
  
    <script> 
    window.onload = createScriptDynamically(); 
    function createScriptDynamically() { 
          
        // Set the url to the web service API from where  
        // the data to be retrieve 
        var url =  
        "https://itunes.apple.com/search?term=taylor+swift&limit=5&callback=processData"; 
          
        // Create the script element dynamically through JavaScript  
        var scriptElement = document.createElement("script"); 
          
        // Set the src and id attributes of the script element 
        scriptElement.setAttribute("src", url); 
        scriptElement.setAttribute("id", "jsonp"); 
        var oldScriptElement= document.getElementById("jsonp"); 
          
        // Get the head element 
        var head = document.getElementsByTagName("head")[0]; 
        if(oldScriptElement == null) {          
          
            /* If there is no script element then append 
            a new element to the head. */
            head.appendChild(scriptElement); 
        } 
        else { 
          
            /* If there is already a element in the head,  
            then replace it with the new script element. */
            head.replaceChild(scriptElement, oldScriptElement);  
        }  
    } 
  
    function processData(myObj) { 
        console.log(myObj); 
          
        /* Function to display the track name and the 
        genre name from the received data. */
        var para = document.getElementById("paragraphElement"); 
          
        for(var i = 0; i < myObj.resultCount; i++){ 
            para.innerHTML = para.innerHTML + myObj.results[i].trackName  
               + "[" + myObj.results[i].primaryGenreName + "]" + "<br>" ;  
        }  
    } 
</script> 
</body> 
</html>

输出:

Delicate [Pop]
Look What You Made Me Do [Pop]
Shake It Off [Pop]
You Belong With Me [Country]
Blank Space [Pop]

以上就是JSONP是什么的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JSON 答疑