国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Ajax跨域?qū)崿F(xiàn)代碼(后臺jsp)

2019-11-19 17:49:24
字體:
供稿:網(wǎng)友

AJAX 教程

AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。

在應(yīng)用時主要是創(chuàng)建XMLHttpRequest對象,調(diào)用指定服務(wù)地址。

但是IE中各個版本支持的不太一樣,所以在創(chuàng)建次對象時可能要特殊處理下。

一般如下:

function createXMLHttpRequest(){ var xmlhttp; try{  xmlhttp = new XMLHttpRequest();//ie7及以上,其他瀏覽器 }catch(e){  try{   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");//ie6  }catch(e){   try{    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//ie6以下   }catch(e){    throw "創(chuàng)建AJAX對象失敗!";   }  } } return xmlhttp; } var xmlhttp = createXMLHttpRequest();  xmlhttp.open("GET","http://localhost:8080/SimpleBlog/AjaxTest",true);  xmlhttp.send(null);  xmlhttp.onreadystatechange = function(result){  if(xmlhttp.readyState==4 && xmlhttp.status == 200){   alter(result.test);  } };

但是瀏覽器再執(zhí)行javascript代碼時,有個著名的同源策略,這使得跨域請求就不是那么方便了。

那一般都是用什么方式支持跨域呢?

1、通過中間代理服務(wù)器,獲取要跨域請求的數(shù)據(jù)。

2、通過iframe內(nèi)嵌帶請求域的頁面,來解決跨域訪問問題。

3、通過jsonp方式。

4、不過現(xiàn)在已經(jīng)提出了XMLHttpRequest Level2(XHR2)允許跨域請求,不過要在server的返回頭中顯示聲明允許跨域請求(瀏覽器的支持情況:http://caniuse.com/#feat=xhr2)。

下面簡單說下jsonp與xtr2。

jsonp:

jsonp簡單的說就是利用<script>標(biāo)簽來實現(xiàn)跨域請求的調(diào)用,因為瀏覽器中腳本的加載是不受同源策略影響的。

function get() {  var url = 'http://localhost:8080/SimpleBlog/AjaxTest?callback=callback';  var script = document.createElement('script');   script.setAttribute("type","text/javascript");   script.src = url;   document.body.appendChild(script);  }  function callback(va){  alert(va.test); }

服務(wù)端(java):

 boolean jsonP = false; String cb = this.request.getParameter("callback"); if (cb != null) { jsonP = true; response.setContentType("text/javascript"); } else {  response.setContentType("application/x-json"); } PrintWriter out = response.getWriter(); if (jsonP) {  try {   out.println(cb + "({/"test/":/"1/"})");   out.flush();   out.close();  } catch (Exception e) {   throw e;  } }

這樣就可以實現(xiàn)跨域調(diào)用了。

而我們經(jīng)常用的jquery已經(jīng)實現(xiàn)了此類方式的封裝,使用起來更簡單。

$(document).ready(function (){  $('#jqueryajax').bind('click', function(){  $.ajax({   type: 'get',   async: false,   url: 'http://localhost:8080/SimpleBlog/AjaxTest1',   dataType: 'jsonp',   jsonp: 'callback',   success: function(json){    alert(json.result);   },   error: function(){    alert('fail');   }  });  }); });

服務(wù)端(java):
我用了struts是這樣寫的:

public class AjaxTest1 extends ActionSupport { private String result; public String getResult() {  return result; }  public String execute() {   this.result = "1";  return "jqueryajax"; }}

配置文件:

<action name="AjaxTest1" class="AjaxTest1"> <result name="jqueryajax" type="json">  <param name="callbackParameter">callback</param> </result> </action>

下面說說xtr2:

這個就更簡單了,直接創(chuàng)建調(diào)用即可。

function createCORSRequest(method,url){  var xhr=new XMLHttpRequest();  if('withCredentials' in xhr){  xhr.open(method,url,true);  }else if(typeof XDomainRequest!='undefined'){   xhr=new XDomainRequest();    xhr.open(method,url);  }else{   xhr=null;  }  return xhr; }  function xhr2(){  var request=createCORSRequest('GET','http://localhost:8080/SimpleBlog/AjaxTest1');  if(request){  request.onload=function(){   alert(request.responseText);  }  request.onerror=function(e){   alert('error');  }  request.send();  }  }

服務(wù)端:其實只要在返回response中設(shè)置
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
即可。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 双辽市| 青阳县| 合阳县| 松滋市| 浏阳市| 平南县| 通城县| 洪湖市| 福海县| 万州区| 昌平区| 诏安县| 阳江市| 赞皇县| 彩票| 门源| 化德县| 海安县| 油尖旺区| 大城县| 西乡县| 盐城市| 和林格尔县| 佛坪县| 宁都县| 武宁县| 南安市| 浦城县| 安福县| 巍山| 无极县| 苗栗市| 大田县| 淳安县| 安泽县| 西乡县| 灵寿县| 莆田市| 当阳市| 当阳市| 忻州市|