首頁  >  文章  >  web前端  >  json原理分析及實例介紹_javascript技巧

json原理分析及實例介紹_javascript技巧

WBOY
WBOY原創
2016-05-16 17:47:451176瀏覽

這次在專案中前後台的數據互動中用到了json,經過這段時間的使用,大概了解了一下,簡單總結一下json。
JSON:JavaScript 物件表示法(JavaScript Object Notation)。
JSON 是儲存和交換文字資訊的語法。類似 XML。
JSON 比 XML 更小、更快,也更容易解析。
和 XML 一樣,JSON 也是基於純文字的資料格式。由於 JSON 天生是為 JavaScript 準備的,因此,JSON 的資料格式非常簡單,您可以用 JSON 傳輸一個簡單的 String,Number,Boolean,也可以傳輸一個數組,或者一個複雜的 Object 物件。
先看controller中的一段程式碼。看主要是看從資料庫查詢出來的資料是怎麼以json的格式輸出的。
[java]

複製程式碼 程式碼如下:

@RequestMapping("/work🎜>

@RequestMapping("/work🎜>

@Re /plan/checkSubmitForApproval")
public void checkSubmitForApproval(String planId,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{ res ;
HttpSession session = request.getSession();
String industryID = (String) session.getAttribute("industryID");
IIndustry industry = industryService.getB .getType().equals("XXX")){
try {
boolean flag = false;
IProjectMain yearPlan = projectPlanService.findProjectPafflanById(planId);
ListISaffuS. getStaffByPlanId(planId, industryID);
for(int i=0;iif(listStaffInfo.get(i).getPractitionersPost().equals(StaffRoleGER. toString())){
flag = true;
}
}
if(flag == true){
result="{"result":"success","personSituation" :"" yearPlan.getPerson_Situation() ""}";
}else{
result="{"result":"success","personSituation":"" yearPlan.getPerson_Situation() "","isManager ":"false"}";
}
} catch (Exception e) {
result="{"result":"falid"}";
throw new PlatformException(e);
}finally{
OutputUtils.write(response,result,"text/x-json;charset=UTF-8");
}

先的write程式碼
[java] 複製程式碼
程式碼如下:



程式碼如下:



程式碼如下:



程式碼如下:



程式碼如下:public static void write(HttpServletResponse response, String text, String contentType)
{
PrintWriter out=null;
response.setHeader("Pragma", "No-cacheull;
response.setHeader("Pragma", "No-cache");res. setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType(contentType);
try
{
out = response.getWriter();
out.write(text);
} }
}
}


其中的想法是得到response的printwriter,將要輸出的資訊設定到其中。在界面層利用jquery的Post判斷回傳的資訊。
[javascript]




複製程式碼


程式碼如下:
function distribute(){
var dplanId = $(".currli").attr("id");
if(dplanId != ""){
$.ajax({
type : "POST",
url :做驗證的action url,
dataType : "json",
success : function(data) {
// HAVE為已指派狀態
if (data.result == "success" && data.personSituation == "UNHAVE") { with (document.getElementById("planForm")) { action=驗證合法後要提交的url; method="post"; submit(); } } 其中success:function(data)是一個回呼函數,即上面做的驗證action的方法成功之後執行的操作。不理解的同學,點這裡學習。非常方便,省去了從xml中一點一點讀取的頭疼,為開發帶來了極大方便。
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn