zoukankan      html  css  js  c++  java
  • 简单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:没有深究,能正常使用就可以了。嘻嘻

  • 相关阅读:
    【linux之web服务器apache】
    【linux工具之sed实例】
    【linux工具之strace】
    【linux工具之iptables 脚本】
    【linux工具之iptables】
    【Linux抓包工具之tcpdump】
    【抓包工具之wireshark】
    【Linux 基础服务之DNS】
    c语言
    sf
  • 原文地址:https://www.cnblogs.com/echoou/p/9176803.html
Copyright © 2011-2022 走看看