2015-04-08 08:09 2,665 人阅读
一、js原生发送Ajax请求
关于Ajax的简单介绍,可以戳此:DOM笔记(五):JavaScript的常见事件和Ajax小结
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>demo</title> </head> <body> <button id="btn">ajax加载</button> <div id="div1"> <p>下面是ajax加载的内容</p> <p id="ajaxcontent"></p> </div> </body> <script type="text/javascript"> //返回xhr实例 function createXHR() { if(window.XMLHttpRequest) { XMLHttpRequest(); } else { ActiveXObject("Microsoft.XMLHTTP"); } } //xhr事件处理 function xhrHandle() { var xhr = createXHR(); var res; xhr.onreadystatechange=function() { if(this.readyState === 4) { if(this.status >= 200 && this.status < 300) { document.getElementById('ajaxcontent').innerHTML = this.responseText; } else { document.getElementById('ajaxcontent').innerHTML ='Error'; } } } xhr.open('GET','./ajaxdemo.php?a=12&b=34'); xhr.send(null); } document.getElementById('btn').addEventListener('click',xhrHandle,false); </script> </html>
对于get请求,send()不带参数,或者设置null。若send()要带参数,则必须为post请求,还需要设置请求头
xhr.open('POST','./ajaxdemo.php'); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xhr.send('a=56&b=78');
ajaxdemo.php:
<?php $fir = $_POST['a']; $sec = $_POST['b']; echo "a=",$fir,'<br/>','b=',$sec; ?>
加载前
加载后
二、JQuery的Ajax请求方式
1、load(url.param,callback):向url发送一个带可选参数param的Ajax请求,可指定一个回调函数。
url必选,Ajax请求地址(字符串)
param可选,指定请求所带的参数(字符串|对象|数组);若指定为对象或者数组(键值对方式),则发起POST请求,若为字符串,则发起GET请求。
callback(response,status,xhr)可选,请求完成时调用的函数。
额外的参数可选
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>demo</title> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> </head> <body> <div id="div1"> <p>下面是ajax加载的内容</p> <p id="ajaxcontent"></p> </div> </body> <script type="text/javascript"> $('#ajaxcontent').load('./ajaxdemo.php',{a:342,b:'test'}); </script> </html>
效果同上类似。load()也可以直接加载xml、html或者html的某个片段内容。
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>demo</title> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> </head> <body> <div id="div1"> <p>下面是ajax加载的内容</p> <p id="ajaxcontent"></p> </div> </body> <script type="text/javascript"> $('#ajaxcontent').load('./ajaxhtml.html #ajaxhtml'); </script> </html>
加载ajaxhtml.html中 id是ajaxhtml的片段。ajaxhtml.html如下
ajax下面是ajax要加载的内容demo.html文件中请求了这里的数据
结果:
2、$.get/post(url,param,callback,type):向url发送带参数的get请求,返回xhr实例
url必选,Ajax请求地址(字符串)
param可选,指定请求所带的参数(字符串|对象|数组)
callback(response,status,xhr)可选,请求完成时调用的函数。
额外的参数可选
type可选。规定预计的服务器响应的数据类型。默认地,jQuery 将智能判断。
可能的类型:
界面采用上面的,修改js
$('#btn').on('click',function(){ $.get('./demo.txt',function(res) { $('#ajaxcontent').text(res) }); });
从demo.txt中加载一段文本,保存为utf-8编码,不然中文会乱码
$.post()形式和$.get()基本一样,不再赘述。
3、$.getJSON(url,param,callback):向url发起GET请求,把响应结果转为JSON字符串,传递给callback。返回xhr实例。相当于在$.get()中,type指定为json.