Ajax Data Request Server for Integration of Front-End Note Points & Resolving Cross-Domain & Three-Level Linkage & session & Stack

1. JSON data at the back end of the request

JSON is an interactive format for front-end and back-end communication. JSON(JavaScript Object Notation, JS Object Markup) is a lightweight data exchange format.

JSON is a necessary format for communication between backstage and predecessors of the Internet, replacing the original XML.

XML data formats are particularly disgusting, and more than 99% of the data formats on the market today are JSON.

In our work, the back end (Java, PHP, Node) provides us with JSON format data, and then we use Ajax to request JSON data, rendering JSON data in the front page. But the data returned to us by the server is the string JSON, so there is no way to dot the call attributes. Now we will learn how to parse the JSON returned to us by the back end.

1.1 JSON analytical method 1

Get JSON interface data in PHP:

l. You will find that the data returned to us by the server is the string JSON, so you can't point out the call attributes.

l In PHP, you can change an array to JSON, using json_encode (array)


The json_db.php backend provides JSON data:


    //Analog with an array and return it to the client JSON Format data
    $arr = array("result"=> array(
            array("name" => "Li Bai", "age" => 31, "sex"=>"male"),
            array("name" => "Su Shi", "age" => 32, "sex"=>"male"),
            array("name" => "Wang Anshi", "age" => 33, "sex"=>"male"),
            array("name" => "Du Fu", "age" => 34, "sex"=>"male"),
            array("name" => "Li Qingzhao", "age" => 35, "sex"=>"female")

    echo json_encode($arr); //Change the array to JSON


The front end requests the interface provided by php to get the data rendered on the page

 $.get("php/json_db.php", function(data){
var dataObj = JSON.parse(data); //Converts the string returned from the back end to JSON object

//Loop traversal output
    for(var i = 0; i < dataObj.result.length;i++){
        var arr = dataObj.result[i];
        //Upper tree
        $("ul").append("<li>"+ arr.name + arr.age + arr.sex +"</li>")

JSON.parse()        take JSON Formal string conversion to JSON object
JSON.stringify()   take JSON Object to String


Get the data in the database and return it to the front end in JSON format:

The data_db.php backend provides JSON data:

    //Connect database, parameters: database address, user name, password
    mysql_connect('localhost', 'root', '123456');
    //Select the database to operate on
    //Set encoding
    mysql_query("SET NAMES utf8");
    //Write to perform insertion SQL Statement, saved to tables in the database
    $sql = "SELECT * FROM gz0902";
    //implement SQL Statement that returns the result of successful insertion (number of bars)
    $result = mysql_query($sql);

    $arr = array(); //Empty array, added by loop traversal

    //Loop traversal assignment, added to the array
    while($row = mysql_fetch_array($result)){
        array_push($arr, $row);
    //output JSON
    $resultJSON = array("result" => $arr);
    echo json_encode($resultJSON);



Front-end parsing JSON

$.get("php/data_db.php", function(data){
   //take JSON Formal Strings Converted to True JSON object
   var dataObj = typeof data == "object" ? data : JSON.parse(data);
   for(var i = 0; i < dataObj.result.length;i++){
       var arr = dataObj.result[i];
       $("ul").append("<li>"+ arr.name + arr.age + arr.sex +"</li>")


1.2 JSON analytical method 2

Overview: eval() is the default function of the system and the method of windows object, so it can be omitted for direct use of windows.

The eval() function can turn a string into a statement and execute it as JavaScript code.

eval() is used as little as possible, but because of its good compatibility, it should also be used when it is used.

Why not recommend eval for JavaScript?


var str = "alert(1+2+3)";

var data = "({a:100,b:200})";
var data = "{a:100,b:200}";
console.log(eval("("+ data +")"))

var fun = "function fun(){alert(1)};fun()";

$.get("php/json_db.php", function(data){
    //take JSON Formal Strings Converted to True JSON object
    var dataObj = eval("(" + data + ")");

1.3 JSON analytical method 3

The third method is to use JS's built-in constructor, new Function().

Parameters: From the first to the penultimate are all parameters, and the last parameter is the program to be executed.

Function() functions convert strings into statements:

var sum = new Function("a","b","c","return a+b+c");

// Equivalent to
function sum(a,b,c){
   return a+b+c;

$.get("php/json_db.php", function(data){
   //take JSON Formal Strings Converted to True JSON object
   var dataObj = (new Function("return" + data)());



II. B/S Structure


Summary: Ajax is a technology that follows the "homology strategy", which means that Ajax cannot cross domains.

Homologous Policy: It is a well-known security policy proposed by Netscape, which is now used by all JavaScript-enabled browsers.

So-called homology strategy: domain name, protocol and port are the same.

When two tab pages of a browser open separately: Baidu and Google pages

When the browser's Baidu tab page executes a script, it checks which page the script belongs to.

That is, check if the script is homologous to Baidu, only the script that is homologous to Baidu will be executed.

If it is not homologous, the browser will report an exception in the console to deny access when requesting data.

Cross-domain: In fact, access to data that is not on the same server forms cross-domain.

For example: the teacher's server IP is, but access to a student's server files, resulting in cross-domain, will report errors.

2.1 Ajax cannot cross domains

Overview: Ajax can not cross-domain, such as our program, can not access Baidu, Taobao, Jingdong server data.

<script type="text/javascript">
     $.get("", function(data){

Tip: Just simulated the request data between two servers, you will find that Ajax can not cross domain.


2.2 JSONP cross-domain

It is also possible to request data across domains, but Ajax is not a good technology, while JSONP is a data format that can be cross-domain. Many years ago, browsers did not have cross-domain restrictions and could normally cross-domain. Browsers restricted Ajax cross-domain for security and privacy.

We can solve this problem by some data means:

Why use cross-domain? Use cross-domain or steal data when requests are not on the same server.

Realization: In HTML, using script tag to refer to this js file is actually to execute the function of the referencing file, when the function is defined in HTML.


The principle of JSONP is to put the part of function execution on the server.

<script type="text/javascript">
    function fun(data){
<script src=""></script>

Tip: This is the teacher's local static page. When visiting a classmate server, the data returned comes from a classmate server.

Place the part of the function execution on the server. When your server wants to get data from other servers, you have to declare a function with the same name as other servers.


This is data:

fun({"name":"Chen Xue Ning","age":16, "sex":"female"});

Tip: How to achieve it?

Answer: The src attribute in the script tag points to an address and makes a request.


Advantages and disadvantages of JSONP:


Un l ike sending Ajax requests using XHR objects, JSONP can span the Same-Origin strategy.

JSONP has good compatibi l ity and can run in many browsers.


1. Support only one type of HTTP requests from GET, with limited application scenarios;

l. Lack of necessary prompt information when the call fails, which makes it inconvenient to troubleshoot the problem.

There are some security risks, but Referer and Token check can be used to avoid them.

l. Not easy to control;

l. No callback function.

2.3 Native JSONP Spanning Request Data

    <button id="btn">Initiation of requests( JSONP)</button>
<script type="text/javascript">
     var btn = document.getElementById("btn");

     //Definition of function
     function fun(data){

     //Initiate the request and get the function execution
     btn.onclick = function(){
        //Establish script Label and specify the requested data address
        var oscript = document.createElement('script');
        oscript.src = "";
        //Upper tree
        //Cross the river, tear down the bridge, take down the tree

Tip: After a request is made by the script tag, the data can be retrieved, and then the elements can be trees without affecting the returned data.


callback in Url corresponds to the name of the function.

Tip: If you want to get JSONP data from other servers, you must declare a function with the same name (or rename it).

<script type="text/javascript">
    function fetchJSON_comment98(data){
<!-- <script type="text/javascript" src=""></script> -->
<script src=""></script>
<script src="https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=598283&score=1&sortType=5&page=0&pageSize=10&isShadowSku=0&fold=1"></script>

2.4 Encapsulation of native JSONP functions

Summary: Encapsulate a function that requests data from other servers across domains. Users only need to pass in URLs and function names.

<script type="text/javascript">
     var btn = document.getElementById("btn");

     function JSONP(url, callback){
        //Name incoming anonymous functions and define them globally
        window.fun = callback;
        //Establish DOM
        var oscript = document.createElement('script');
        oscript.src = url;
        //Upper tree
        //Crossing the river, tearing down the bridge, taking down the tree

     //Initiate request
     btn.onclick = function(){
        JSONP("", function(data){
            console.log(data);  //Data data is passed from the execution of the function

2.5 jQuery's JSONP cross-domain

Overview: jQuery encapsulates JSONP, and jsonCallback is the name of the function passed in.


Get JSON data for a server:

   jsonpCallback:"fun", //Function name


Data from Jingdong Review:


When using jQuery to cross the domain, the callback in the url is followed by the name of the function, or you can modify the name of the function yourself.

If the url callback is followed by a? Number, instead of writing the jsonpCallback callback function, jQuery will randomly name the function.


Here's jQuery's random function name.


2.6 Level 3 Linkage

    <select id="province"></select>
    <select id="city"></select>
    <select id="area"></select>
<script type="text/javascript" src="js/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
        //turn JSON object
        var dataObj = JSON.parse(data);
        //Cycling all the data to get the provinces on the tree
        $.each(dataObj.all, function(key,value){
            // console.log(key,value);
            var $option = $("<option>"+ value.name +"</option>");

        //When the provincial data transmission changes, perform the following methods
        var cityArr = [];
        $("#province").on("change", function(){
            //Get the name of the province you are currently choosing
            var pro = $("#province option:selected").text();

            //Travel through provinces and get cities
            $.each(dataObj.all, function(item,val){
                if(val.name == pro){
                    for(var i = 0; i < val.city.length;i++){
                        $("<option>" + val.city[i].name + "</option>").appendTo('#city');

                    //Ergodic obtainable region
                    $.each(val.city[0].area, function(index,val){
                        $("<option>" + val + "</option>").appendTo('#area');


        //When the city changes, trigger, change the district.'
        $("#city").on("change", function(){
            $("#area").empty(); //Empty content
            //Get the currently selected city name
            var city = $("#city option:selected").text();

            for(var i = 0; i < cityArr[0].length;i++){
                if(cityArr[0][i].name == city){
                    $.each(cityArr[0][i].area, function(index, val){
                        $("<option>" + val + "</option>").appendTo('#area');

        //Page loading initializes city data

Three, effect

3.1 Loaded Display-Native Route

<style type="text/css">
        width: 300px;
        height: 300px;
        background: url('./images/loading.gif') no-repeat;
    img{display: none;}
        <img src="./images/19.png" >
<script type="text/javascript">
     var img = document.getElementsByTagName('img')[0];
     //When the picture is loaded, it is displayed
     img.onload = function(){
        img.style.display = 'block';

3.2 Complete Loading Display-jquery Routine

Image is a built-in constructor in the system, so it can be used directly and returns an img element object.

    <div id="box"></div>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    // var img = document.createElement('img');
    var img = new Image();
    img.src = "./images/18.png";

    //Up the tree after loading

Chat Room

Chat room production ideas:

Users click on login to pass the input username to Login.php. Login.php regularly verifies the validity of the username after receiving it. If A-1 is returned to the front-end illegally, exit returns.
The front end receives a return of -1 and reminds the user to re-enter. If it is legal, it opens session_start() and stores the user name, $_SESSION[name]=$name; and returns a 1 to the front end.
The front-end receives a successful login, jumps to the chat page (with Chinese remember to declare utf-8 encoding), opens the session, reads the user name, judges when the user presses the return bus, writes the user name and the input content into the database.
When the database meets again, it accepts data, connects to the database, inserts data, and executes this data: $result=mysql_query($sql); if it is true, it returns 1, otherwise it returns - 1,
When the function in the chat page request receives 1, it empties the input box. At first, it has a scroll bar and the scroll value is its own high. Open a timer, empty the content of the chat box, request JSON data from the database get, and connect to the database.
Read the data table and sort it (remember to declare JSON) to execute the table, declare an array, it has a maximum key, loop to take the items from the data table, there is a variable, push this variable to the key of the largest data we declare,
Its value is an array, in pint_r output, remember to convert this array into JSON, chat page receives the return value of its largest key and then saves a variable, loop this variable, and dot to take the data tree, timer interval request.


Summary: HTTP Hypertext Transfer Protocol, which belongs to short polling links, initiates a request and disconnects after a response.

The PHP session variable is used to store information about user sessions or to change the settings of user sessions. The Session variable holds information for a single user and is available to all pages in the application.


Tip: session PHP has, JS has, it is a background to the front-end users sent a'token', can distinguish who is who;


Use of Session:

Session is different from cookie. Session_start() must be started first.

When you first visit a website, the Session_start() function creates a unique Session_ID. This Session_ID is automatically saved to the client's coookie through the HTTP response header. At the same time, a file named Session_ID is created on the server side for saving.

This user's session information. When the same user visits the website again, the session_ID saved in the cookie is automatically brought back through the HTTP request header. At this time, the Session_start() function will not allocate a new Session_ID again, but will search for a Session file with the same name of Session_ID in the server-side hard disk to save the previous pseudo-user. Read out the conversation information. In the current script application, to achieve the purpose of tracking users.


Tip: The regular method preg_match (regular string, string) in PHP returns a Boolean value, and exit is the return statement in PHP.

Free API Interface




Five. Review

5.1 Basic Types and Reference Types

JavaScript language has: language core, DOM, BOM, review language core.

What are the data types of JavaScript?
    Basic type values: number, string, boolean, undefined, null
    Reference type values: Object, Array, Function, RegExp, Math, Date

Why distinguish between basic types and reference types? There are two differences:

The way to distinguish is to distinguish according to the location stored in memory.

Basic type: The space occupied in memory is fixed size. Their values are stored in stack memory and accessed by values.

Reference type: The size is not fixed, and the address where they are stored in stack memory points to the object in heap memory, which is accessed by reference.

5.2 stack memory and heap memory

The stack allocates space automatically and releases space automatically.

heap allocates memory space dynamically, and does not automatically release space.

Media stored in a computer:

Hard Disk: Documents, Music, Video, Documents, etc. (After the computer is powered off, the data remains), storage space [240G, 500G, 1T, 2T]

Memory: Storage medium, read and write faster than hard disk (computer power off data is gone). Storage space [2G,4G,8G]

CPU cache: temporary memory located between CPU and memory. When the computer is powered off, the data is lost and the storage space [256KB, 2M, 4M, 8M].


There are five main spaces in memory: heap, stack, free storage, global, constant.

Distinction 1: The basic type is "stack memory" storage in memory, and the reference type value is "heap memory" storage.

First, what is memory?


How much memory can a computer store?

Computer system digits: 32 bits, 64 bits

Take 64 bits as an example: a memory bar contains 64 bits of binary value, which is 8 bytes.

The memory bar 4G space equals 4*1024*1024*1024*1024 bytes and 4*1024*1024*1024*1024*1024*1024*8 bytes. Five hundred and thirty-six million eight hundred and seventy thousand nine hundred and twelve

The memory bar 8G space equals 8 * 1024 * 1024 * 1024 bytes, and 8 * 1024 * 1024 * 1024 * 1024 8 bytes. One billion seventy-three million seven hundred and forty-one thousand eight hundred and twenty-four


The information stored in memory has corresponding addresses.


The basic type values are all in a small cell in memory. If the string is too long, the memory will be planned in the form of a "linked list", and then it will be considered in an address.

What is a "stack", similar to the structure of a CD-ROM rack, or a badminton cone. First put in, must be the last taken out, in and out at one end, belongs to the "first in last out" [FILO]



Memory bars are called stack memory. The essential reason is that memory maintains a list of "blank areas":


Now, according to the figure above, if the programmer wants vara = 1, then this 1 is written to 45533 address, because it is the top of the stack, 45533 is "out of the stack".

Then var b=2; at this time b is written on 45534, because at this time the top of the stack is 45533, it is "out of the stack".

Write vara = haha at this time, when a is released, 45533 returns to the top of the stack, when it is rewritten as "haha", then it goes out of the stack again. A small cell equal to 45533 changes from 1 to Haha.


Referring to type values, memory is handled by heap memory:

Var arr=[1,2,3,""J,""Q,""Xiaowang"];


This is called heap memory.

Distinction 2: When the basic type is assigned, a copy will be cloned in memory at this time; the reference type will only pass the address.


 Var arr=[1,2,3,'J','Q','Xiaowang'];

 var b = a;


Changes to a also affect b.

Note: The base type is destroyed at the end of the execution environment, while the reference type is not destroyed at the end of the execution environment. Only when all the variables referring to it do not exist, the object is reclaimed by the garbage collection mechanism.

Keywords: Javascript JSON PHP Database

Added by Chappers on Wed, 15 May 2019 22:03:54 +0300