zoukankan      html  css  js  c++  java
  • 前端之json,ajax和jsonp

    json

    json是 JavaScript Object Notation 的首字母缩写,单词的意思是javascript对象表示法,这里说的json指的是类似于javascript对象的一种数据格式,目前这种数据格式比较流行,逐渐替换掉了传统的xml数据格式。

    javascript对象字面量:

    var oMan = {
        name:'tom',
        age:16,
        talk:function(s){
            alert('我会说'+s);
        }
    }

    json格式的数据:

    {
        "name":"tom",
        "age":18
    }

    与json对象不同的是,json数据格式的属性名称需要用双引号引起来,用单引号或者不用引号会导致读取数据错误。

    json的另外一个数据格式是数组,和javascript中的数组字面量相同。

    ["tom",18,"programmer"]

    配置服务器环境-node.js的简单使用

    C:Usersusername>node -v
    v7.4.0
    
    C:Usersusername>e:
    
    E:>cd E:PycharmPycharm_savecp155前端5jQuery和js库4jQuery第四天
    
    E:PycharmPycharm_savecp155前端5jQuery和js库4jQuery第四天>node server.js
    Static file server running at
      => http://localhost:8888/
    CTRL + C to shutdown

    使用node.js运行的小型服务器文件:server.js

    /*
    NodeJS Static Http Server - http://github.com/thedigitalself/node-static-http-server/
    By James Wanga - The Digital Self
    Licensed under a Creative Commons Attribution 3.0 Unported License.
    
    A simple, nodeJS, http development server that trivializes serving static files.
    
    This server is HEAVILY based on work done by Ryan Florence(https://github.com/rpflorence) (https://gist.github.com/701407). I merged this code with suggestions on handling varied MIME types found at Stackoverflow (http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs).
    
    To run the server simply place the server.js file in the root of your web application and issue the command 
    $ node server.js 
    or 
    $ node server.js 1234 
    with "1234" being a custom port number"
    
    Your web application will be served at http://localhost:8888 by default or http://localhost:1234 with "1234" being the custom port you passed.
    
    Mime Types:
    You can add to the mimeTypes has to serve more file types.
    
    Virtual Directories:
    Add to the virtualDirectories hash if you have resources that are not children of the root directory
    
    */
    var http = require("http"),
        url = require("url"),
        path = require("path"),
        fs = require("fs")
        port = process.argv[2] || 8888;
    
    var mimeTypes = {
        "htm": "text/html",
        "html": "text/html",
        "jpeg": "image/jpeg",
        "jpg": "image/jpeg",
        "png": "image/png",
        "gif": "image/gif",
        "js": "text/javascript",
        "css": "text/css"};
    
    var virtualDirectories = {
        //"images": "../images/"
      };
    
    http.createServer(function(request, response) {
    
      var uri = url.parse(request.url).pathname
        , filename = path.join(process.cwd(), uri)
        , root = uri.split("/")[1]
        , virtualDirectory;
      
      virtualDirectory = virtualDirectories[root];
      if(virtualDirectory){
        uri = uri.slice(root.length + 1, uri.length);
        filename = path.join(virtualDirectory ,uri);
      }
    
      fs.exists(filename, function(exists) {
        if(!exists) {
          response.writeHead(404, {"Content-Type": "text/plain"});
          response.write("404 Not Found
    ");
          response.end();
          console.error('404: ' + filename);
          return;
        }
    
        if (fs.statSync(filename).isDirectory()) filename += '/index.html';
    
        fs.readFile(filename, "binary", function(err, file) {
          if(err) {        
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(err + "
    ");
            response.end();
            console.error('500: ' + filename);
            return;
          }
    
          var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
          response.writeHead(200, {"Content-Type": mimeType});
          response.write(file, "binary");
          response.end();
          console.log('200: ' + filename + ' as ' + mimeType);
        });
      });
    }).listen(parseInt(port, 10));
    
    console.log("Static file server running at
      => http://localhost:" + port + "/
    CTRL + C to shutdown");
    server.js

    ajax

    ajax技术的目的是让javascript发送http请求,与后台通信,获取数据和信息。ajax技术的原理是实例化xmlhttp对象,使用此对象与后台通信。ajax通信的过程不会影响后续javascript的执行,从而实现异步。

    同步和异步
    现实生活中,同步指的是同时做几件事情,异步指的是做完一件事后再做另外一件事,程序中的同步和异步是把现实生活中的概念对调,也就是程序中的异步指的是现实生活中的同步,程序中的同步指的是现实生活中的异步。

    局部刷新和无刷新
    ajax可以实现局部刷新,也叫做无刷新,无刷新指的是整个页面不刷新,只是局部刷新,ajax可以自己发送http请求,不用通过浏览器的地址栏,所以页面整体不会刷新,ajax获取到后台数据,更新页面显示数据的部分,就做到了页面局部刷新。

    同源策略
    ajax请求的页面或资源只能是同一个域下面的资源,不能是其他域的资源,这是在设计ajax时基于安全的考虑。特征报错提示:

    XMLHttpRequest cannot load https://www.baidu.com/. No  
    'Access-Control-Allow-Origin' header is present on the requested resource.  
    Origin 'null' is therefore not allowed access.

    $.ajax使用方法
    常用参数:

    1. url 请求地址
    2. type 请求方式,默认是'GET',常用的还有'POST'
    3. dataType 设置返回的数据格式,常用的是'json'格式,也可以设置为'html'
    4. data 设置发送给服务器的数据
    5. success 设置请求成功后的回调函数
    6. error 设置请求失败后的回调函数
    7. async 设置是否异步,默认值是'true',表示异步

    以前的写法:

    $.ajax({
        url: 'js/data.json',
        type: 'GET',
        dataType: 'json',
        data:{'aa':1}
        success:function(data){
            alert(data.name);
        },
        error:function(){
            alert('服务器超时,请重试!');
        }
    });

    新的写法(推荐):

    $.ajax({
        url: 'js/data.json',
        type: 'GET',
        dataType: 'json',
        data:{'aa':1}
    })
    .done(function(data) {
        alert(data.name);
    })
    .fail(function() {
        alert('服务器超时,请重试!');
    });
    
    // data.json里面的数据: {"name":"tom","age":18}

    jsonp

    ajax只能请求同一个域下的数据或资源,有时候需要跨域请求数据,就需要用到jsonp技术,jsonp可以跨域请求数据,它的原理主要是利用了script标签可以跨域链接资源的特性。

    jsonp的原理如下:

    <script type="text/javascript">
        function aa(dat){
            alert(dat.name);
        }
    </script>
    <script type="text/javascript" src="....../js/data.js"></script>

    页面上定义一个函数,引用一个外部js文件,外部js文件的地址可以是不同域的地址,外部js文件的内容如下:

    aa({"name":"tom","age":18});

    外部js文件调用页面上定义的函数,通过参数把数据传进去。


    json简单使用示例(在sever.js被node运行的条件下,有一个叫data.json的文件存储数据)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $.ajax({
                    url: 'data.json',
                    type: 'get',
                    dataType: 'json'
                })
                    .done(function (dat) {
                        $('#username').html(dat.name);
                        $('#userage').html(dat.age);
    
                    })
                    .fail(function () {
                        alert('服务器超时!');
                    })
            })
        </script>
    </head>
    <body>
    <p>姓名:<span id="username"></span></p>
    <p>年龄:<span id="userage"></span></p>
    </body>
    </html>
    json简单使用示例

    生鲜首页获取json数据制作欢迎用户登录

    <script type="text/javascript">
            $(function () {
                $.ajax({
                    url:'js/data.json',
                    type:'get',
                    dataType:'json'
                })
                .done(function(dat){
    
                    $('.user_login_btn').hide();
    
                    $('.user_info em').html(dat.name);
    
                    $('.user_info').show();    
                    
                })
                .fail(function(){
                    alert('服务器超时!')
                })
            })
    </script>
    
    <body>
        <!--  页面顶部     -->
        <div class="header_con">
            <div class="header">
                <div class="welcome fl">欢迎来到天天生鲜!</div>
                
                <div class="top_user_info fr">
                    <div class="user_login_btn fl">
                        <a href="">登录</a>
                        <span>|</span>
                        <a href="">注册</a>
                    </div>
    
                    <div class="user_info fl">
                        欢迎您:<em>张三</em>
                    </div>
    
                    <div class="user_link fl">
                        <span>|</span>
                        <a href="">我的购物车</a>
                        <span>|</span>
                        <a href="">我的订单</a>
                    </div>
                </div>
            </div>        
        </div>
    </body>
    首页获取用户信息并欢迎

    jsonp的简单使用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            $.ajax({
                url: 'js/data.js',
                type: 'get',
                dataType: 'jsonp',
                jsonpCallback: 'fnback'
            })
                .done(function (dat) {
    
                    alert(dat.name);
                })
        </script>
    </head>
    <body>
    </body>
    </html>
    
    //data.js
    //fnback({'name':'tom'});
    jsonp的简单使用

    jsonp练习-360联想词获取

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            // https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8
            // &format=json&fields=word&word=d
    
            $(function () {
                $('#input01').keyup(function () {
                    var $val = $(this).val();
    
                    $.ajax({
                        url: 'https://sug.so.360.cn/suggest?',
                        type: 'get',
                        dataType: 'jsonp',
                        data: {'word': $val}
                    })
                        .done(function (data) {
                            //console.log(data);
                            // 清空元素里面的内容
                            $('#list01').empty();
    
                            var dat = data.s;
                            for (var i = 0; i < dat.length; i++) {
                                var $newli = $('<li>');
    
                                $newli.html(dat[i]);
    
                                $newli.appendTo($('#list01'));
                            }
                        })
                })
            })
        </script>
    </head>
    <body>
    <input type="text" name="" id="input01">
    
    <ul id="list01"></ul>
    </body>
    </html>
    jsonp-360联想词获取示例
  • 相关阅读:
    消息队列 资源不足,无法执行操作
    内存级的缓存实际上引用
    Vs 2013 单步调试 .net framework 中遇到的问题
    Win7总是显示“软件应用无法兼容”的解决方法
    Win10系统文件受损怎么办
    教你win10系统如何一键修复系统
    Win10专业版如何提升游戏流畅度
    win7电脑任务管理器被停用如何解决
    win7系统移动硬盘打不开解决方法
    Java之集合(五)LinkedList
  • 原文地址:https://www.cnblogs.com/yifchan/p/html-1-11.html
Copyright © 2011-2022 走看看