• JSONP跨域 ajax请求


     

    原理:

    由于浏览器的同源策略不能使用XMLHTTPREQUEST对除本地外的服务器发送请求。

    所以使用script代码块的src属性发送请求,接收到的JSONP数据以函数名的方式返回。

    需要在本地创建服务器返回的函数接收服务器返回的数据。


    JS代码:

    function jsonpRequest() {
    var create_src = document.createElement('srcipt'); #创建script标签
    create_src.src = 'http://127.0.0.1:8000/index.html?callback=func';    #给script标签加入src请求地址
    document.head.appendChild(create_src);      #把script标签添加到head标签内
    document.head.removeChild(create_src);      #把script标签在head标签内删除

    }

    function f(arg) {
    console.log(arg)
    }



    jquery代码:

    $.ajax({
    url:'http//xxxxx',
    type:'GET' 或 'POST',
    dataType:JSONP,
    jsonp:'callback',
    jsonpCallback:'func'
    })

    function func(arg){
      console.log(arg);
    }


    django代码:

    def jsonp_func(request):
      name = request.GET.get('callback')
      return HttpResponse('%s,***' % name)
  • 相关阅读:
    php+ajax文件上传
    安装ruby及sass
    大佬
    ES6--let,解构赋值,promise && ES7--async
    miniapp基础
    8月笔记
    webpack 打包html文件
    webpack压缩打包不成功
    nvm安装成功后,但命令不可用(command not found)
    jq库extend的区别
  • 原文地址:https://www.cnblogs.com/louzi/p/9248191.html
Copyright © 2020-2023  润新知