AJAX technology junior exploration

A concept

Ajax technology enables a page to obtain information from the server asynchronously, without refreshing the page

Ajax's core technology is the XMLHttpRequest object (XHR)

Asynchronous code is actually requested data does not block execution down the page

Two primeval Ajax

1 Create XMR objects

    var xhr=new XLMHttpRequest();

2 Open Request | prepare request

    xhr.open ( parameters )      

Parameters are as follows: 

Request type get (content request address spliced)

post (non-address transmission)

Request path js / data.json  

If the request after the path get through? Splicing parameters, parameters & connection

Boolean true if the asynchronous to synchronous asynchronous false

The default ture is executed asynchronously

3 transmits a request

    xhr.send();   

Send the data transferred to the background in

           get request is null (the address of the request parameters in the request later)

           post request may set transmission parameters, it is null if not 

In the format of "uname = zhangsan & upwd = 123"

    Note: Add code analog form submission before submitting post

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

4 is determined in response to

    Asynchronous request

       1 binding listen for events onreadystatechange

2 Get response status codes readyState, determines whether the reception completion

4 illustrates a receiving end to readyState

       Response result determination 3

           xhr.status     200 for the request was successful  

Request path 404 is absent

500 server internal abnormalities 

       4 fetch response data

           xhr.responseText   data server response (possibly a variety of formats)

xhr.onreadystatechange = function(){

   if (xhr.readyState == 4) {

      if (xhr.status == 200) {

          console.log(xhr.responseText);

      }

   }

}

Synchronization request does not need to monitor the status code

Mihara package raw Ajax

1 defines the calling object

       Address request whether the request type asynchronous data upload information processing method

was u1 = {

    method:"GET",

    url:"js/data.json?key=a&uname=zhangsan&upwd=12345",

    async:true,

    data:{

           uname:"zhangsan",

           upwd:"123456"

    },

    success:function(result){

           console.log(result);

    }

};

       Note: Parameters result data processing method The results are shown in ajax callback data.

Performing data processing result of the data processing method.

Package 2

       A core create XMLHttpRequest Object

       Code:

var xhr = new XMLHttpRequest();

       Formatting parameters B

              This procedure removed the call object parameters, assigned to the variable. The main content is spliced with the traverse

Request type (uppercase rpm)

Request address (get request in character stitching)

Whether asynchronous

Upload information (to a string)

Data processing method

param = obj.dat to have;

// convert json object format for parameters specified format string

    uname=zhangsan&upwd=12345

var paramArray = [];

// iterate parameter object

for (var key in param) {

// stitching parameter name and value

       var pa = key+"="+param[key];

// append data to the array

       paramArray.push(pa);

}

// array into a string designated by the symbol

var p = paramArray.join("&");

// get the user request type

var method = obj.method.toUpperCase();

// request type is determined, if the request is GET, behind the splicing request address request parameters

if (method == "GET") {

"?" // determine whether the address included, if so, when using mosaic "&"; if not, use the "?"

    obj.url +=(obj.url).indexOf("?") > -1  ? "&" + p:"?" + p;

}

       Opening request C   

xhr.open(method,obj.url,obj.async);

       D request submitted

              Before submitting the request to add the analog form and submit before post way

              Submit code, the requested content is added to the post submission process

// If it is a POST request, you need to simulate form submissions

if (method.toUpperCase() == "POST") {

// analog form submission

    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

    // post提交

    xhr.send(p);

} else {

       // get提交

       xhr.send(null);

}

        E 响应判断

              分别对异步同步执行对应的流程

              设置回调函数 调用传入的数据处理方法对服务端响应的数据进行处理

判断是否是否是异步请求

if (obj.async) { // 异步请求

// 监听readySate的值,判断响应是够完毕

    xhr.onreadystatechange = function() {

// 如果完全响应,值为4

    if (xhr.readyState == 4){callback();}

    }

} else { // 同步请求

    callback();

    }

// 回调函数

function callback() {

// 判断是否响应成功  status=200

if (xhr.status == 200) {

    // 得到相应数据,并回调数据给调用者

    var result = xhr.responseText;

    obj.success(result);

    }

}

三 通过JQuery使用Ajax

JQuery中封装了Ajax

调用格式

普通调用

    $.ajax(参数);  参数为json对象

       json对象的参数包括

    {   type: "get",                 或者”post”

       url: "js/data.json",          目标地址

       data:{ },                   传入的数据

       dataType: "json"                服务器返回的数据类型

       success:function(result){对result的操作代码}

}  

以下为具体内容

type:请求方式 GET/POST

url:请求地址 url

async:是否异步,默认是 true 表示异步

data:发送到服务器的数据

dataType:预期服务器返回的数据类型

contentType:设置请求头

success:请求成功时调用此函数

error:请求失败时调用此函数

get调用

    $.get(参数)    通过逗号分隔 省略key值

$.get("js/data.json",{},function(data){console.log(data);});

post调用

    $.post(参数)   通过逗号分隔 省略key值

$.post("js/data.json",{},function(data){console.log(data);});

getJSON调用       属性通过逗号分隔 省略key值

$.getJSON("js/data.json",{},function(data){console.log(data);});

 

跨域调用

    两个域名,从一个域名访问另一个的域名 需要通过jsonp方式发送请求

    条件    1远程接口支持跨域访问

2 ajax中设置dataType:"jsonp" [jsonp:’callback’]

$.ajax({

   type:"get",

   url:"http://iservice.itshsxt.com/restaurant/find",

   data:{ },

   dataType:"jsonp",

   success:function(result){console.log(result);}

});

三 eclipse中web项目的设置

调出server窗口

    window菜单->show view ->other ->查找servers 选中打开窗口

创建server

    右击new ->server -> 选中Apache下的Tomcat版本 next->

选择tomcat目录(选bin的父目录)  选中jdk next ->完成

启动tomcat测试

注意:Tomcat的默认接口8080,与oracle冲突,需要手动关oracle服务或改端口

 

创建web项目

文档框new选择other.查找web 选择Dynamic Web Project  设项目名一路确认

在tomcat上右击选择(add and move) 在左右选框中移动项目

 

web项目中webContent下创建页面和资源文件 webContent与src都相当于根目录

    访问地址 localhost:端口号/项目名/(webContent下的直接目录)

Guess you like

Origin www.cnblogs.com/javaxiaobu/p/11128595.html