zoukankan      html  css  js  c++  java
  • ajax跨域请求

    1.一般我们在ajax中跨域请求资源时,浏览器控制台会报如下错误:

    代码:

    $.ajax({
    
        url:"http://127.0.0.1:8000/get_data.html",
        success:function (response) {
            alert(response)
        }
    })

    错误:

    原因是因为,跨域的返回值的response中,缺少了一个header值:Access-Control-Allow-Origin,导致被浏览器拦截....,这称之为浏览器的同源策略.

    这时,我们提供2个方法.

    方法1:jsonp

    代码

    $.ajax({
        url: "http://127.0.0.1:8000/get_data.html",
        type: "GET",
        dataType: "JSONP",
        jsonp: "callback",
        jsonpCallback: "list666"
    });
    function list666(arg) {
        alert(arg)
    }

    原理:

      1.带src属性的标签如img,script,iframe不受同源策略约束

      2.上述jsonp代码的原理展示如下,就是通过构建一个script标签,将src的值赋予它,然后将它添加到head,执行时,从网址拿到数据,数据是list666("机密数据"),引发该函数执行.

    function list666(arg) {
        alert(arg)
    }
    function jsonp() {
        var spt = document.createElement("script");
        spt.src = "http://127.0.0.1:8000/get_data.html?callback=list666"
        document.head.appendChild(spt)
    }
    jsonp()

      3.同时需要请求的那个网站做如下处理:

    def get_data(request):
        func_name = request.GET.get("callback")
        return HttpResponse("%s('机密数据')" % func_name)

    方法2:CORS,即:跨域资源共享(CORS,Cross-Origin Resource Sharing),其本质是设置响应头,使得浏览器允许跨域请求。

    前端正常请求:

    $.ajax({
        url: "http://127.0.0.1:8000/get_data.html",
        type: "GET",
        success:function (arg) {
            alert(arg)
        }
    });

    所跨域的后端添加请求头信息:

    def get_data(request):
        response = HttpResponse('机密数据')
        response['Access-Control-Allow-Origin'] = "http://127.0.0.1:8005"
        return response

    处理简单请求时上述代码即可,如处理复杂请求,如put,自定制请求头,则需要在经过2次发送,第一次是预检,预检成功才会继续发送请求.

    response中需要添加如下信息,

    response['Access-Control-Allow-Origin'] = "http://127.0.0.1:8888"
    response['Access-Control-Allow-Methods'] = "PUT"
    response['Access-Control-Allow-Headers'] = "xxx"

    更多信息:ajax全套     JavaScript、Dom和jQuery

  • 相关阅读:
    Palindrome Partitioning
    Minimum Path Sum
    Maximum Depth of Binary Tree
    Minimum Depth of Binary Tree
    Unique Binary Search Trees II
    Unique Binary Search Trees
    Merge Intervals
    Merge Sorted Array
    Unique Paths II
    C++ Primer Plus 笔记第九章
  • 原文地址:https://www.cnblogs.com/jec1999/p/7684387.html
Copyright © 2011-2022 走看看