前端之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:\Users\username>node -v
v7.4.0

C:\Users\username>e:

E:\>cd E:\Pycharm\Pycharm_save\cp15\05前端\05jQuery和js庫\04jQuery第四天

E:\Pycharm\Pycharm_save\cp15\05前端\05jQuery和js庫\04jQuery第四天>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\n");
      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 + "\n");
        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\n  => http://localhost:" + port + "/\nCTRL + 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聯想詞獲取示例

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM