前面的一篇博文简单的简绍了Ajax基于jQuery的用法,接下来要对Ajax做进一步的介绍,
Ajax请求大致可以通过三种方式发送:原生Ajax,jQuery,伪Ajax。
1.原生Ajax:
由于Ajax是以XML的格式和后台进行数据传输,所以原生的Ajax即是通过XMLHttpResponse
对象来完成请求
XMLHttpResponse对象使用方法:
<script> ???????function Ajax1() { ???????????var xhr=new XMLHttpRequest(); ???????????xhr.open(‘POST‘,‘/ajax_json/‘,true);//打开 ???????????xhr.onreadystatechange=function () { ???????????????if(xhr.readyState==4){ ???????//表示接受完毕 ???????????????????????res=xhr.responseText; ???//拿到返回的值 ???????????????????console.log(res) ???????????????} ???????????????xhr.setRequestHeader(‘k1‘,‘v1‘);//请求头 ???????????????xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded; charset-UTF-8‘); ???????????????xhr.send(‘name=root;pwd=123‘); ?//开始发送,只能发送字符串 ???????????} ???????} ???????function submitLoad() { ???????????$(‘#ifml‘).load(function () { ???????????????var v=$(this).contents().find(‘body‘).text() ???????????????var obj=JSON.parse(v) ???????????????console.log(obj) ???????????}) ???????} ???</script>
2.伪Ajax:
HTML中的iframe标签可以实现在本页面中加载内容,所以可以利用iframe这一特性
来实现类似Ajax请求的功能而不需要通过XML的方式,称之为‘伪Ajax’
<form action="/ajax_json/" method="POST" target="ifml"> ???????<iframe id="ifml" name="ifml"></iframe><br> ???????<input type="text" name="user" placeholder="username"><br> ???????<input type="text" name="email" placeholder="email"> ???????<input type="submit" value="form" onclick="submitLoad()"> ???</form> ???<script> ???????function submitLoad() { ???????????$(‘#ifml‘).load(function () { ???????????????var v=$(this).contents().find(‘body‘).text() ???????????????var obj=JSON.parse(v) ???????????????console.log(obj.data) ???????????}) ???????} ???</script>
web前端开发-Ajax(2)
原文地址:http://www.cnblogs.com/SunsetSunrise/p/7794931.html