JavaScript JSONP

JavaScript JSONP

什么是JSONP?

XMLHttpRequest(XHR)可以用来从服务器获取数据。一旦数据在浏览器中接收到,可以使用JSON.parse()方法将接收到的JSON字符串转换为JavaScript对象。但是,XHR存在同源安全性问题。这意味着从某个域请求页面,比如ADomain.com,然后该页面通过XMLHttpRequest从BDomain.com获取一些数据,浏览器会拒绝此请求。这是因为该请求是由不同于页面所提供的域进行的。只有当XMLHttpRequest发送到ADomain.com时,它才能接收回数据,因为XHR只在请求发送到同一域时起作用。

JSONP(带填充的JSON): 这是一种通过避免跨域问题来获取数据的方法。使用<script>标记来实现。

JSON和JSONP之间的区别:

  • JSON: JavaScript使用JSON(JavaScript对象表示法)在网络上交换数据。仔细查看JSON数据,它实际上是一个JavaScript对象的字符串格式。

    示例:

{"name":"GFG", "id":1, "articlesWritten":5}
  • JSONP: JSONP是带填充的JSON。这里,填充是指在请求返回之前将一个函数包装在JSON周围。

    示例:

GeeksFunction({"name":"GFG", "id":1, "articlesWritten":5});

使用JSONP的方法:

  • 在HTML代码中,包含<script>标签。该标签的来源将是要检索数据的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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程