json front end of, ajax and jsonp

json

json JavaScript Object Notation is the first letter of the abbreviation, is the meaning of the word javascript object notation, said here refers to a similar javascript json object to a data format, the current data format more popular, and gradually replace the traditional xml data format.

javascript object literal:

was Oman = {
    name:'tom',
    age:16,
    talk:function(s){
        Alert ( 'I would say' + S);
    }
}

json formatted data:

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

The difference is that the object json, json property name data format required by double quotes, with or without single quotation marks cause read data error.

Another json data format is an array, the array and the literal is the same as javascript.

["tom",18,"programmer"]

 

 

Configure the server environment -node.js simple to use

C:\Users\username>node -v
v7.4.0

C:\Users\username>e:

E: \ > cd E: \ PyCharm \ Pycharm_save \ CP15 \ 05 front-end \ 05jQuery and js library \ 04jQuery Day

E: \ Pycharm \ Pycharm_save \ cp15 \ 05 front-end \ 05jQuery and js library \ 04jQuery fourth day > the Node server.js
Static file server running at
  => http://localhost:8888/
CTRL + C to shutdown

 

Using node.js server running a small files: 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

The purpose is to enable javascript ajax technology to send http request, to communicate with the background, access to data and information. Ajax principle of the technique is an example xmlhttp objects, using the object to communicate with the background. Ajax process does not affect the execution of subsequent communications javascript, thereby asynchronous.

Synchronous and asynchronous
real life, synchronization refers to do several things at the same time, asynchronous refers to finish a job to do another thing, synchronous and asynchronous program is to swap the concept of real life, that is, program asynchronous refers to the real-life synchronization, program synchronization refers to the real-life asynchronous.

 

No partial refresh and refresh
ajax partial refresh can be achieved, also called non-refresh, refresh-free refers to the entire page does not refresh, only a partial refresh, you can send your own http ajax request, not through the browser address bar, so the whole page will not refresh, ajax get to the back-end data, update parts of the page data show that it did partial page refresh.

 

Origin policy
ajax request a page or resource is only following the same domain resources, it can not be resources to other domains, which is based on safety considerations in the design of ajax. Feature error prompt:

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 to use
common parameters:

  1. url request address
  2. type request mode, the default is 'GET', commonly used as well as 'POST'
  3. dataType set to return a data format commonly used is 'json' format may be set to 'html'
  4. setting data transmitted to the data server
  5. Set after the success callback request is successful
  6. Set the error callback request failed
  7. async settings are asynchronous, the default value is 'true', showing asynchronous

Previous wording:

$.ajax({
    url: 'js/data.json',
    type: 'GET',
    dataType: 'json',
    data:{'aa':1}
    success:function(data){
        alert(data.name);
    },
    error:function(){
        Alert ( 'server timeout, please try again!' );
    }
});

The new wording (recommended):

$.ajax({
    url: 'js/data.json',
    type: 'GET',
    dataType: 'json',
    data:{'aa':1}
})
.done(function(data) {
    alert(data.name);
})
.fail(function() {
    Alert ( 'server timeout, please try again!' );
});

// the data.json data inside: { "name": "tom ", "age": 18}

 

jsonp

ajax requests only under the same domain data or resources, sometimes need to request data across domains, you need to use jsonp technology, jsonp can request data across domains, its main principle is to use the script tag can link resources across domains characteristic.

jsonp works as follows:

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

 

A function is defined on the page, a reference to an external file js, js external file address may be an address different domains, external js file contents as follows:

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

External js file calls the function defined on page parameter transfers the data into it.

 


json simple example used (at node is running sever.js with a data file stored in the called 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 ( ' server timeout! ' );
                })
        })
    </script>
</head>
<body>
<p>姓名:<span id="username"></span></p>
<p>年龄:<span id="userage"></span></p>
</body>
</html>
json using simple examples

Fresh Home Get json data made welcome user login

<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 ( ' server timeout! ' )
            })
        })
</script>

< Body > 
    <-!   Top of the page      -> 
    < div class = "header_con" > 
        < div class = "header" > 
            < div class = "FL is available for purchase" > Welcome to the Fresh every day! </ 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" > 
                    Welcome: < EM > John Doe </ EM > 
                </ div >

                <div class="user_link fl">
                    <span>|</span>
                    <a href="">我的购物车</a>
                    <span>|</span>
                    <a href="">我的订单</a>
                </div>
            </div>
        </div>        
    </div>
</body>
Home users get information and welcome

 

Simple use of 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'});
Simple use of jsonp

jsonp get word association exercise -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) {
                         // the console.log (Data); 
                        // Clear the contents inside the element 
                        $ ( ' # list01 ' ) .empty ();

                        was dat = data.s;
                        for ( were in =  0 ; in < dat.length; in ++ ) {
                             were $ 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 Lenovo word for examples

 

Guess you like

Origin www.cnblogs.com/yifchan/p/html-1-11.html