Ajax原生与jQuery

来源:互联网 发布:网络科学导论期末考试 编辑:程序博客网 时间:2024/06/05 13:05

四步走:

  1.创建XMLHttpRequest核心对象;

  2.注册监听;

  3.建立连接;

  4.发送数据;

第一步:创建XMLHttpRequest核心对象

varxhr = newXMLHttpRequest();

兼容写法:

   function getXhr(){

    varxhr=null;

   if(window.XMLHttpRequest){

  xhr=newXMLHttpRequest();

   }else{

  xhr=newActiveXObject("Microsoft.XMLHttp");

   }

   return xhr;

}

第二步:注册监听

xhr.onreadystatechange = function(){

  if(xhr.readyState === 4 &&xhr.status === 200){

  varjson =eval("("+xhr.responseText +")");

  fn(json);

  }

  }

readyState(状态值)

  存有XMLHttpRequest的状态。从04发生变化。

  0: 请求未初始化

  1: 服务器连接已建立

  2: 请求已接收

  3: 请求处理中

  4: 请求已完成,且响应已就绪 

status(状态码)

200:"OK“

304:文件未改变,页面缓存

404:未找到页面

500:后台的问题

第三步:建立连接

xhr.open(method,url,async);

method:请求类型,分为getpost方式;格式为字符串;

url:请求地址;格式为字符串;

Async:是否异步;(true:异步;false:同步)

例如:xhr.open(“get”,www.baidu.com,false);

第四步:发送数据

Get方式与post方式发送的参数不一样

格式:xhr.sendstring);

get方式请求时,发送null

post方式请求时,发送具体参数

getpost的区别?

1.一般,get是从服务器上获取数据,post是向服务器传送数据。

2.get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTPpost机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。

3.对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。

4.get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。

5.get安全性非常低,post安全性较高。但是执行效率却比Post方法好。

建议:

1、get方式的安全性较Post方式要差些,包含机密信息的话,建议用Post数据提交方式;

2、在做数据查询时,建议用Get方式;而在做数据添加、修改或删除时,建议用Post方式;


创建XMLHttpRequest对象

functioncreateXHR(){

  if(window.XMLHttpRequest){

  return new XMLHttpRequest(); //IE6以上版本

  }

  else{

  return newActiveXObject("MSXML2.XMLHTTP"); // IE6浏览器

  }

}

functiongetAjax(url,fn){

  // url = "地址"

  // fn = function callback(data){

  //   console.log(data);

  // }

  var xhr = createXHR();

  xhr.open("GET",url,true);

  xhr.onreadystatechange = function(){

  if(xhr.readyState === 4 && xhr.status=== 200){

  var json = eval("("+xhr.responseText +")");

  fn(json);

  }

  }

  xhr.send(null);

}

functionpostAjax(url,param,fn){

  var xhr = createXHR();

  xhr.open("POST",url,true);

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

  xhr.onradystatechange = function(){

  if(xhr.readyState === 4 && xhr.status=== 200){

  var json = eval("("+xhr.responseText +")");

  fn(json);

  }

  }

  xhr.send(param);

}

为什么浏览器不能跨域

同源策略,所谓同源是指,域名,协议,端口相同。它是浏览器的一种最核心最基本的安全策略。它对来至不同源的文档或这脚本对当前文档的读写操作做了限制。

为什么要有这个策略,想必你已经知道,那就是因为保证用户的信息安全。

src可以跨域

在这里需要注意的是,文档中的所有带“src”属性的标签都可以跨域加载资源,而不受同源策略的限制。

如<script>、<img>、<iframe>、<link>等。如果你在页面定义了这些标签,在页面加载事都对不同源的资源发起了一次GET请求。但是通过src加载的资源,浏览器限制了脚本对其返回的内容无法读写。特别是在ajax请求的时候,特别要注意XMLHttpRequest的时候是无法跨域访问的。

jsonp跨域

<!DOCTYPEhtml>

<html>

<head>

  <meta charset="utf-8">

  <title>JSONP跨域</title>

</head>

<body>

  <scripttype="text/javascript">

  //url,创建script便签

  function requestJSONP(url) {

  var script =document.createElement("script");

  script.src = url;

  document.body.appendChild(script);

  }

  function jsonp4(data) {

  console.log(data);

  }

requestJSONP("https://api.douban.com/v2/movie/in_theaters?start=0&callback=jsonp4");

  //Geonames API:邮编的位置信息

  //requestJSONP("http://www.geonames.org/postalCodeLookupJSON?postalcode=10504&country=US&callback=jsonp4");

  </script>

</body>

</html>

ajax跨域(后台允许)

<!DOCTYPEhtml>

<html>

  <head>

  <meta charset="utf-8" />

  <title></title>

  <style>

  *{margin:0px;padding:0px;}

  p,span{border:1px solidred;display:inline-block;text-align: center;}

  </style>

  </head>

  <body>

  <input type="text"value="" id="input1"/>

  <div id="div1">

  </div>

  </body>

<!--<scriptsrc="https://api.douban.com/v2/movie/in_theaters"></script>-->

  <script>

     varinputadd=document.getElementById("input1");

    inputadd.addEventListener('input',function(){

       varkeys=inputadd.value;

      //console.log(keys);

  function getXhr(){

  var xhr=null;

  if(window.XMLHttpRequest){

  xhr=new XMLHttpRequest();

  }else{

  xhr=newActiveXObject("Microsoft.XMLHttp");

  }

  return xhr;

  }

functiongetAjax(url,fn){

  var xhr=getXhr();

  xhr.open('get',url,true);

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

  xhr.onreadystatechange=function(){

  if(xhr.status==200){

  if(xhr.readyState==4){

  vardatajson=eval("("+xhr.responseText+")");

  //var datajson =JSON.parse(xhr.responseText);//跨域

  fn(datajson);

  }

  }

  }

  xhr.send(null);

  //xhr.send();

  }

getAjax("http://m.ctrip.com/restapi/h5api/searchapp/search?source=mobileweb&action=autocomplete&contentType=json&keyword="+keys,function(data){

  vardiv=document.getElementById("div1");

  //div.innerHTML=data.data[0].url;

  var divhtml="";

  console.log(data);

  for(var i=0;i<data.data.length;i++){

  divhtml+="<span><ahref='"+data.data[i].url+"'>"+data.data[i].word+"</a></span><br/>";

  }

  div.innerHTML=divhtml;

  })

     })

  </script>

</html>

jQuery  ajax

get()方法通过远程 HTTP GET 请求载入信息。

这是一个简单的GET 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。

语法

$(selector).get(url,data,success(response,status,xhr),dataType)

该函数是简写的Ajax 函数,等价于:

$.ajax({

  url: url,

  data: data,

  success: success,

  dataType: dataType

});


举例:

<script>

  $(document).ready(function(){

   $("button").click(function(){

     $.get("data/data1.json",function(data){

          //alert(data[0]);

        vardiv=document.getElementById("div1");

  for(var i=0;i<data.length;i++){

  div.innerHTML+="<span>"+data[i].id+"</span>"+

  "<span>"+data[i].name+"</span>"+

  "<span>"+data[i].price+"</span>"+

  "<span>"+data[i].count+"</span><br/>";

  }

 

      });

    });

  })

  </script>

post()方法通过 HTTP POST 请求从服务器载入数据。

jQuery.post(url,data,success(data,textStatus, jqXHR),dataType)

该函数是简写的Ajax 函数,等价于:

$.ajax({

  type: 'POST',

  url: url,

  data: data,

  success: success,

  dataType: dataType

});


举例:

<!DOCTYPEhtml>

<html>

<head>

<scriptsrc="/jquery/jquery-1.11.1.min.js">

</script>

<script>

$(document).ready(function(){

  $("button").click(function(){

   $.post("/example/jquery/demo_test_post.asp",{name:"Donald Duck",city:"Duckburg"},

    function(data,status){

      alert("数据:" + data +"\n状态:" + status);

    });

  });

});

</script>

</head>

<body>

<button>向页面发送HTTP POST 请求,并获得返回的结果</button>

通过HTTP GET 请求载入 JSON 数据。

在jQuery 1.2 中,您可以通过使用 JSONP 形式的回调函数来加载其他网域的 JSON 数据,如"myurl?callback=?"。jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。注意:此行以后的代码将在这个回调函数执行前执行。

语法

jQuery.getJSON(url,data,success(data,status,xhr))

该函数是简写的Ajax 函数,等价于:

$.ajax({

  url: url,

  data: data,

  success: callback,

  dataType: json

});


例子1

从Flickr JSONP API 载入 4 张最新的关于猫的图片:

HTML代码:

<divid="images"></div>

jQuery代码:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?

tags=cat&tagmode=any&format=json&jsoncallback=?",function(data){

 $.each(data.items, function(i,item){

   $("<img/>").attr("src",item.media.m).appendTo("#images");

   if ( i == 3 ) return false;

 });

});

例子2

从test.js 载入 JSON 数据,附加参数,显示 JSON 数据中一个 name 字段数据:

$.getJSON("test.js",{ name: "John", time: "2pm" }, function(json){

  alert("JSON Data: " +json.users[3].name);

});