zoukankan      html  css  js  c++  java
  • jsonp的原理及其使用

    原理:

      1.创建script标签

      2.src远程地址

      3.返回的数据必须为js格式

    1.因为浏览器处于安全原因不允许跨域请求,但是允许跨域倒入js文件,所以需要创建script标签

    2.src远程地址,这里的地址代表着接口地址,因为接口提供的数据为js文件格式,里面有对应的function和数据。

    3.接口的数据为js格式,浏览器会认为程序在倒入新的js文件,就会允许倒入数据,通过倒入这些数据,可以将这些数据提交给后台处理。

    例:获取江西电视台的接口数据

    from django.contrib import admin
    from django.urls import path
    from app01 import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('req/', views.req),
    ]
    urls.py
    from django.shortcuts import render
    import requests
    
    # Create your views here.
    
    def req(request):
        response = requests.get('http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301')
        response.encoding = 'utf-8'
        return render(request, 'req.html', {'response':response.text})
    views.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h3>request获取的数据</h3>
        {{ response }}
    
        <h3>js获取结果</h3>
        <!--xhr获取数据-->
        <input type="button" value="获取数据" onclick="getContent()">
    
        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            function getContent() {
                /* xhr只能做同一域名的http请求,对于不同域名,浏览器禁止跨域请求 */
                /*
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403');
                xhr.onreadystatechange = function () {
                    alert(xhr.responseText);
                };
                xhr.send();
                */
    
                /* jsonp通过引入js文件方式获取接口数据。(接口的返回值为相应数据以及需要调用的function名称) */
                /*
                var tag = document.createElement('script');
                tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403';
                document.head.appendChild(tag);
                document.head.removeChild(tag);
                */
    
                /* jsonp通过js获取接口数据 */
                $.ajax({
                    url: 'http://www.jxntv.cn/data/jmd-jxtv2.html',
                    type: 'POST',
                    dataType: 'jsonp',
                    jsonp: 'callback',
                    jsonpCallback: 'list'
                })
            }
            
            function list(arg) {
                console.log(arg)
            }
        </script>
    </body>
    </html>
    req.html

    前端引入接口数据有两种方法,一种是通过dom添加标签的方式,通过<script>标签引入js文件内容,另一种就是通过js的ajax方法,固定格式获取数据。

  • 相关阅读:
    398. Random Pick Index
    382. Linked List Random Node
    645. Set Mismatch
    174. Dungeon Game
    264. Ugly Number II
    115. Distinct Subsequences
    372. Super Pow
    LeetCode 242 有效的字母异位词
    LeetCode 78 子集
    LeetCode 404 左叶子之和
  • 原文地址:https://www.cnblogs.com/ttyypjt/p/10391587.html
Copyright © 2011-2022 走看看