• 简单ajax跨域请求


    最近遇到需要ajax跨域的需求

    首先看下不做任何处理特别处理的ajax跨域请求会出现什么样的错误

    客户端代码:

    <script type="text/javascript">
        $.ajax({
            url: 'http://localhost/test/respone.php',
            type: 'get',
            dataType: 'json',
            success:function (res) {
                console.log(res);
            }
        });
        
    </script>

    服务端代码:

    <?php
    echo json_encode(['name'=>'ogq','age'=>18]);
    
    ?>
    

    运行结果:

    提示:Failed to load http://localhost/test/respone.php: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://my.com' is therefore not allowed access.错误

    这是因为浏览器ajax不能跨域造成的,下面是我查找资料后简单做的一个ajax跨域请求与返回

    客户端代码:

    <script type="text/javascript">
        $.ajax({
            url: 'http://localhost/test/respone.php',
            type: 'get',
            dataType: 'jsonp',
            success:function (res) {
                console.log(res);
            }
        });
        
    </script>
    

      没错,只是将dataType:"json" 改成了“jsonp”,

    然后是服务器端代码:

    <?php
    
    echo $_REQUEST['callback'],'('.json_encode(['name'=>'ogq','age'=>18]),')';
    ?>
    

      在请求一次,输出结果

    这样就能正常跨域了

    ps:没有深究,能正常使用就可以了。嘻嘻

  • 相关阅读:
    Chapter 1. 数据库(介绍、主键、外键)
    练习、悬浮标签、导航菜单
    Chapter 3. document对象
    Chapter 3. JavaScript
    Chapter 2. HTML---CSS样式表(格式与布局)
    Chapter 2. HTML---CSS样式表
    12月26 一维数组
    12月23 语句
    12月23 运算符
    12月21 vs2012 数据类型
  • 原文地址:https://www.cnblogs.com/echoou/p/9176803.html
Copyright © 2020-2023  润新知