当前位置:首页 > Web开发 > 正文

Ajax简单用法

2024-03-31 Web开发

Ajax是啥?
Ajax是允许客户端与处事端通信而无需刷新当前页面的一种技术,不是一种语言。

如何完成一个完整的Ajax交互?
交互分三步:
创建Ajax东西:XMLHttpRequest东西(XMLHttpRequest东西是Ajax的根本)
发送请求:
1.onreadystatechange事件措置惩罚惩罚函数:该函数由处事器触发,而不是由用户触发。在Ajax执行过程中,处事端会向用户端发送当前的状态(通过XMLHttpRequest东西的ReadyState属性)。在请求过程中,该函数会被触发4次。
2.open要领:成立请求open(method,url,asynch)。规定请求方法、地点和是否异步传输。
3.send要领:将请求发送随处事器。如果请求方法是post,send要领可以通报参数
接收响应
1.readyState:存储XMLHttpRequest的状态值(0-4).0:请求未初始化,1:处事器已成立连接,2.请求已接收,,3.请求措置惩罚惩罚中,4.请求已完成,且相应已就绪。当readyState的值产生转变时,会挪用onreadystatechange函数。
2.status:在XMLHttpRequest东西中,处事器发送的状态码都被生存在status属性中。通过将这个属性值与200和304对照,确保处事器是否发送了一个告成的响应。404:没找到界面,403.禁止访谒,500.内部处事器错误,200.一切正常,304.没有被改削。
3.responseText:处事器向客户端发送的文件,它是一个HTML,XML或普通文本,这取决与处事器发送的内容,当readyState状态值变为4时,responseText才可用,表白Ajax请求已结束。
4.responseXML:如果处事器返回的是XML文件,那么数据将存储在responseXML属性中,只有处事器发送了正确的首部地点的信息时,responseXML属性才可用。

下面插入一个简单的demo

var xhr = new XMLHttpRequest(); var testData= {"tempStr":"sss"}; xhr.open("post", ":14104/test/login"); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(null); xhr.onreadystatechange = function () { if (xhr.readystate == 4) { //响应内容解析完成,可以在客户端挪用了 if (xhr.status == 200) { //客户真个请求告成了 console.log(xhr.responseText); } } }

再来一个jquery版本的demo

$.ajax({ //请求方法 type : "get", //请求的媒体类型 contentType: "application/json;charset=UTF-8", //请求地点 url : ":14104/test/login?tempStr=‘sss‘", //数据,json字符串 data : null, //请求告成 success : function(result) { console.log(result); }, //请求掉败,包罗具体的错误信息 error : function(e){ console.log(e.status); console.log(e.responseText); } });

需要注意的事项有以下几点:

1、get方法请求的时候,容易因为易泄露信息而阻止请求。后台需要将JsonRequestBehavior 设置为 AllowGet。我简单写成:return Json(person, JsonRequestBehavior.AllowGet);

2、就是跨域问题,相当尴尬,报个资源加载掉败,完全想不到是跨域问题。熬夜到三点,说多了都是泪。解决要领就是在处事器真个webconfig插手以下代码:

<configuration> <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer> </configuration>

遇到坑继续来填。。。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30365.html