跨域问题–服务器配置(二)

跨域问题–JSONP(一)中使用的是JSONP的hack方式去解决跨越调用的问题。更常规的方式是通过服务器配置。
下面通过配置apache解决跨越问题,nginx的可以根据查询相关资料

修改配置文件httpd.conf
去掉注释LoadModule headers_module modules/mod_headers.so
在节点Directory中添加:

Header set Access-Control-Allow-Origin "*"

remote2.php

<?php
    $a = $_GET['a'];
    $b = $_GET['b'];
    $c = $a + $b;

    echo '{"result":"'.$c.'"}'; //从前台获取a和b,将a+b结果返回到回调函数
?>

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSONP</title>
</head>
<body>
   <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

   <script>
       $.getJSON("http://localhost:8080/remote2.php?a=2&b=9", function(data) {//像调用本地后台方法一样
            alert(data.result);
       })
   </script>
</body>
</html>

跨域问题–JSONP实现(一)

json.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSONP</title>
</head>
<body>
    <script>
        var localHandler = function(data){
             alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
        };
    </script>
    <script src="http://localhost:8080/remote.php?a=7&b=2&cb=localHandler"></script>
</body>
</html>

remote.php

<?php
    $a = $_GET['a'];
    $b = $_GET['b'];
    $c = $a + $b;
    $cb = $_GET['cb'];

    echo "$cb({result: $c})"; //从前台获取a和b,将a+b结果返回到回调函数
?>

启动apache,在浏览器访问:http://localhost:8080/remote.php?a=7&b=2&cb=localHandler
显示文本:

localHandler({result: 9})

跟期望的结果一致。
用浏览器打开在jsonp.html,会弹出对话框打印计算后结果。

jquery对jsonp的支持

后台php代码保持不变,js代码用jquery $.ajax代替

 <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

   <script>
        $.ajax({
             type: "get",
             async: false,
             url: "http://localhost:8080/remote.php?a=7&b=1",
             dataType: "jsonp",
             jsonp: "cb",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"localHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(data){
                 alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
             },
             error: function(){
                 alert('fail');
             }
         });
   </script>

jsonp不是ajax的一个特例,哪怕jquery等巨头把jsonp封装进了ajax,也不能改变着一点!
参考链接:
http://harttle.com/2015/10/10/cross-origin.html
https://segmentfault.com/a/1190000003710973

vue一个简单应用

最近在学习vue,做的一个小的例子程序。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>留言板</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            margin-top: 20px;
        }

        .user-list {
            margin-top: 20px;
            border-top: 1px solid #ccc;
        }

        .user-list h2 {
            text-align: center;
        }

        .user-list th,td {
            text-align: center;
        }

    </style>
</head>
<body>
    <div class="container" id="user-box">
        <form role="form" v-on:keyup.enter="addUser();">
              <div class="form-group">
                <label for="email">姓名</label>
                <input type="text" class="form-control" id="name" v-model="name" placeholder="请输入姓名">
              </div>
              <div class="form-group">
                <label for="age">年龄</label>
                <input type="number" class="form-control" id="age" v-model="age" placeholder="请输入年龄">
              </div>
              <button type="button" class="btn btn-primary" @click="addUser();">添加</button>
              <button type="button" class="btn btn-danger" v-on:click="reset();">重置</button>
        </form>

        <div class="user-list">
            <h2>用户信息表</h2>
            <table class="table table-bordered">
              <tr>
                  <th>序号</th>
                  <th>姓名</th>
                  <th>年龄</th>
                  <th>操作</th>
              </tr>
              <tr v-show="this.users.length == 0">
                  <td colspan="4">暂时没有用户数据</td>
              </tr>
              <tr v-for="(user, index) in users">
                 <td>{{index+1}}</td>
                 <td>{{user.name}}</td>
                 <td>{{user.age}}</td>
                 <td><button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal"
                 v-on:click="nowIdx = index;dialogTitle = '确认删除用户【'+user.name+'】?';">删除</button></td>
              </tr>
              <tr v-show="this.users.length > 0">
                  <td colspan="4"><div class="pull-right"><button type="button" class="btn btn-danger" data-toggle="modal" 
                  data-target="#myModal" v-on:click="index = -1;dialogTitle = '确认删除全部用户?';">删除全部</button></div></td>
              </tr>
            </table>

        </div>

        <div class="modal fade" id="myModal">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <h4 class="modal-title">{{dialogTitle}}</h4>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-danger" v-on:click="makeDel();">确定</button>
                  </div>
                </div><!-- /.modal-content -->
              </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </div>


    <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
    <script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://cdn.bootcss.com/vue/2.0.3/vue.min.js"></script>


    <script src="demo.js"> </script>
</body>
</html>

demo.js

var users = JSON.parse(localStorage.getItem('u')|| "[]");

        new Vue({
            el: '#user-box',
            data: {
                users:  users,
                name: '',
                age: '',
                dialogTitle: '',
                nowIdx: -1
            },
            methods: {
                addUser: function() {
                    this.users.push({"name": this.name, "age": this.age});

                    localStorage.setItem('u', JSON.stringify(this.users));

                    this.reset();
                },
                reset: function() {
                    this.name = '';
                    this.age = '';
                },
                makeDel: function() {
                     if (-1 === this.nowIdx) {
                        this.users = [];
                    } else {
                         this.users.splice(this.nowIdx,1);
                    }
                    $('#myModal').modal('toggle');
                    localStorage.setItem('u', JSON.stringify(this.users));
                }
            }
        });

null

javascript事件传播(三)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>event</title>
    <style>
        #big {
            width: 100px;
            height: 100px;
            background-color: #f00;
        }

         #small {
            width: 50px;
            height: 50px;
            background-color: #ccc;
        }


    </style>
</head>
<body>
    <div id="big">
        <div id="small"></div>
    </div>

    <script>
        var big = document.getElementById('big');
        var small = document.getElementById('small');
        big.addEventListener('click', function() {
            alert('big');
        }, false);


       small.addEventListener('click', function(event) {
            event.stopPropagation(); //停止冒泡
            alert('small');
        }, false);

    </script>
</body>
</html>

javascript操作DOM节点(一)

  • 点击按钮后,对文本进行排序后重新显示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>sort list</title>
</head>
<body>
    <ul id="list">
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
        <li>Four</li>
    </ul>

    <button id="sort-btn">sort</button>

    <script>
       var btn = document.getElementById('sort-btn') ;

       btn.addEventListener('click',sortList, false);


       function sortList() {
         sortKids('list');
       }

       function sortKids(e) {
          if (typeof e === 'string') e = document.getElementById(e);

          var kids = [];
          for (var x = e.firstChild; x != null; x = x.nextSibling) {
            if (x.nodeType == 1) { 
              kids.push(x);
            }
          }

          kids.sort(function(n, m) {
              var nv = n.firstChild;
              var mv = m.firstChild;
              if (nv > mv) return -1;
              return 1;
          });

          for (var i = 0; i < kids.length; i++) {
                e.appendChild(kids[i]);
          }

       }
    </script>
</body>
</html>