传统方法的缺点:
传统的web交互是用户触发一个http请求服务器,然后服务器收到之后,在做出响应到用户,并且返回一个新的页面,每当服务器处理客户端提交的请求时,客户都只能空闲等待,并且哪怕只是一次很小的交互、只需从服务器端得到很简单的一个数据,都要返回一个完整的HTML页,而用户每次都要浪费时间和带宽去重新读取整个页面。这个做法浪费了许多带宽,由于每次应用的交互都需要向服务器发送请求,应用的响应时间就依赖于服务器的响应时间。这导致了用户界面的响应比本地应用慢得多。
什么是ajax?
ajax的出现,刚好解决了传统方法的缺陷。AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
XMLHttpRequest 对象
XMLHttpRequest对象是ajax的基础,XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。目前所有浏览器都支持XMLHttpRequest
abort() | 停止当前请求 |
---|---|
getAllResponseHeaders() | 把HTTP请求的所有响应首部作为键/值对返回 |
abort() | 停止当前请求 |
getResponseHeader(“header”) | 返回指定首部的串值 |
open(“method”,“URL”,[asyncFlag],[“userName”],[“password”]) | 建立对服务器的调用。method参数可以是GET(获取数据) 、POST(新建 增加数据)或PUT(更新 修改数据 删除数据)。url参数可以是相对URL或绝对URL。这个方法还包括3个可选的参数,是否异步, 默认为true异步 同步是false 同步用户名,密码 |
send(content) | 向服务器发送请求(500 服务器报错 404 页面丢失 200 success) |
setRequestHeader(“header”, “value”) | 把指定首部设置为所提供的值。在设置任何首部之前必须先调用open()。设置header并和请求一起发送 (‘post’方法一定要 ) |
五步使用法:
1.创建XMLHTTPRequest对象
2.使用open方法设置和服务器的交互信息
3.设置发送的数据,开始和服务器端交互;send(content)这个方法里面的参数可写可不写 写想服务器传输数据 不写是请求数据
4.注册事件
5.更新界面
同步和异步的区别:
同步是:等待请求完成之后 再去执行 异步是:请求和后续代码同时执行
如何将原生ajax进行封装
封装成一个函数,请求接口时候需要 路径 方式 数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <meta charset= "UTF-8" ><title></title><script> /* get 方式传值 是在url 路径之后?a=1&b=2&n=3 * post 不在路径上写 send() 上发送数据 * */ function method(res, url, data, callback) { var http = new XMLHttpRequest(); if (res == "get" ) { if (data) { url += "?" ; url += data; } http.open(res, url); http.send(); } else { http.open(res, url); if (data) { http.send(data); } else { http.send(); } } http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { callback(JSON.parse(http.response)); } } } method( "post" , "./list/data.txt" , null , function (data) { console.log(data); }); </script> |
JS几种跨域方法和原理
解决ajax跨域
一般ajax跨域解决就是通过JSONP解决或者CORS解决,如以下:
js跨域是指通过js在不同的域之间进行数据传输或通信,跨域 : 协议 端口 主机名称不同会产生跨域
第一种方法:jsonp跨域(只支持get请求)
比如,有个a.html页面,它里面的代码需要利用ajax获取一个不同域上的json数据,假设这个json数据地址是http://example.com/data.php,那么a.html中的代码就可以这样:
实现原理:由于使用script标签调用远程js文件没有不受跨域的影响,所以可以通过创建一个script标签,通过src属性来访问远程文件。
其实这并不属于AJAX,但是可以实现类似AJAX的功能。
第二种方法:cross 跨域 php 在里面配置 header(‘Access-Control-Allow-Origin: * ‘);但只支持HTML5
1 2 3 4 5 6 7 8 | var http = new XMLHttpRequest(); http.send(); http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { console.log(http.response); } } |
第三种方法:代理
这种方式是通过后台(ASP、PHP、JAVA、ASP.NET)获取其他域名下的内容,然后再把获得内容返回到前端,这样因为在同一个域名下,所以就不会出现跨域的问题。
实现代码:创建一个AJAX请求(页面地址为:http://localhost/ajax/proxy.html)
1 2 3 4 5 6 7 8 9 10 | var request = null ; if (window.XMLHttpRequest) { request = new XMLHttpRequest; } else { request = new ActiveXObject( "Microsoft.XMLHttp" ); } request.onreadystatechange = function { console.log( this .readyState); if ( this .readyState===4 && this .status===200) { var resultObj = eval( "(" + this .responseText+ ")" ); //将返回的文本数据转换JSON对象 document.getElementById("box").innerHTML = resultObj.name+":"+resultObj.sex; //将返回的内容显示在页面中 } } request.open("POST","proxy.php",true); request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send("name=吕铭印&sex=男"); |
创建AJAX请求。
proxy.php代码
1 2 3 4 | header( "Content-type:text/html;charset=utf-8" ); $contents = file_get_contents ( $url ); echo $contents ; |
附:ajax跨域post请求的java代理实现
最近开发的项目有个功能的需求如下:根据用户提供的外部链接(outter_url),在页面填写好查询条件(param)并向该url发起查询请求,查询返回的数据来动态生成html的table来显示数据,同时要求请求的方法是post请求。
在开发过程中用的是jquery的异步请求。问题出现了,网上搜了半天没有发现实现jquery跨域进行post请求的解决方案(貌似不支持),所以自己用java代码来发起post跨域请求
关于实现思路的几点说明:
1) 项目中用的是spring,所以这个请求是在spring某个controller的方法中实现的,为了方便说明问题该方法假设为(ajaxProxy)
2) 在jsp页面中通过jquery的ajax方法,发起一个请求,该请求的url映射到1)中所说的那个ajaxProxy方法,并把查询条件(param)一起传递到ajaxProxy方法.部分代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $.ajax({ type : "GET" , //映射到controller对应方法的url url : "<url value=" /user/put/queryItems "></url>" , //查询条件数据 data : param, dataType : 'json' , success : function (data) { //动态生成table,代码略} |
3) 在ajaxProxy方法中,用HttpURLConnection链接outter_url,并设置connection的请求方法为Post,并发送查询条件(param),该部分的代码实现如下:
1 2 3 4 5 6 7 8 | URL connect = new URL(outer_url); HttpURLConnection connection =(HttpURLConnection)connect.openConnection(); Connection.setRequestMethod(“Post”); //发送查询条件 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.wirte(param); out.flush(); |
4) 接收数据并返回数据,jsp页面中ajax的success方法处理接收到的数据data,并把data返回就可以了,接收数据的代码如下
1 2 3 4 5 6 7 8 | StringBuffer data = new StringBuffer(); BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), "gb2312" )); String line; while ((line = reader.readLine()) != null ) { data.append(line); } return data; |
综上所述,实现跨域post请求的java实现代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | @RequestMapping ( "queryItems" ) public @ResponseBody String ajaxProxy(String name, String startTime, String endTime, String tag, Model m, HttpServletRequest req) throws UnsupportedEncodingException { //拼接查询条件,组成json格式的数据发送 JSONObject node = new JSONObject(); try { JSONObject param = new JSONObject(); param.put( "type" , "" ); param.put( "typevalue" , "" ); //param.put("key", name); param.put( "key" , new String(name.toString().getBytes( "utf-8" ), "gbk" )); param.put( "start_time" , startTime); param.put( "end_time" , endTime); param.put( "tags" , tag); node.put( "param" , param); JSONObject user = new JSONObject(); user.put( "userid" , "123" ); node.put( "user" , user); JSONObject device = new JSONObject(); device.put( "dnum" , "123" ); node.put( "device" , device); JSONObject developer = new JSONObject(); developer.put( "apikey" , "******" ); developer.put( "secretkey" , "*****" ); node.put( "developer" , developer); node.put( "action" , action); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 使用POST方式向目的服务器发送请求 URL connect; StringBuffer data = new StringBuffer(); try { connect = new URL( "outter_url" ); HttpURLConnection connection = (HttpURLConnection)connect.openConnection(); connection.setRequestMethod( "POST" ); connection.setDoOutput( true ); OutputStreamWriter paramout = new OutputStreamWriter( connection.getOutputStream(), "UTF-8" ); paramout.write(json); paramout.flush(); BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream(), "gb2312" )); String line; while ((line = reader.readLine()) != null ) { data.append(line); } paramout.close(); reader.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return data.toString(); } |
总结
到此这篇关于AJAX请求数据及实现跨域的三种方法的文章就介绍到这了,更多相关AJAX请求数据及跨域内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!