天天看點

ajax讀取檔案資料,Ajax 實作讀取 properties 格式資源檔案資料

Ajax 的核心是 JavaScript 對象 XmlHttpRequest。該對象在 Internet Explorer 5 中首次引入,它是一種支援異步請求的技術。簡而言之,XmlHttpRequest 使您可以使用 JavaScript 向伺服器提出請求并處理響應,而不阻塞使用者。下面講述一下通過Ajax讀取properties格式資源檔案資料。

1、properties檔案内容如下:userId=yoodb

name=素文宅

[email protected]

address=中國北京市

2、Jquery實作調用Ajax處理代碼,具體如下:$.ajax({

type:'POST',

dataType:'json',

url:'/handleProperties.do',

async:false,

success:function(data){

jsonData = data.jsi18n;//jsi18n是java傳回時賦予的名稱

jsi18n = eval_r('(' +jsonData+ ')');//轉化為json對象(eval_r()函數可計算某個字元串,并執行其中的的 JavaScript 代碼)

alert("property is " + jsi18n.name);

},

error:function(event, XMLHttpRequest, ajaxOptions, thrownError){

alert("error");

}

});

3、Java背景處理properties檔案,具體代碼如下:publicString getResourceBundle(){

ResourceBundle RESOURCE_BUNDLE;

if(contextPvd.getSessionAttr("gLanguage")!=null&&contextPvd.getSessionAttr("gLanguage").equals("1")){

RESOURCE_BUNDLE=ResourceBundle.getBundle("jsi18n",Locale.ENGLISH);

}else{

RESOURCE_BUNDLE =ResourceBundle.getBundle("jsi18n",Locale.CHINA);

}

Set keySet=RESOURCE_BUNDLE.keySet();

//讀取資源檔案資料拼接成json格式字元串傳回

String jsonString = newString();

jsonString+="{";

for(String key:keySet){

jsonString+='"'+key+'"'+":"+'"'+RESOURCE_BUNDLE.getString(key)+'"'+",";

}

//把字元串賦給傳回對象

jsonRoot.put("jsi18n",jsonString.substring(0,jsonString.length()-1)+"}");

return SUCCESS;

}

如果其他函數也需要調用傳回的結果,需要通過Js把傳回值賦給一個全局變量。