我使用Ajax來作出一個servletand請求接收JSON字符串在JavaScript中的JSON字符串解析?
servlet代碼//服務器端
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Content-Type", "text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
try {
ArrayList<SearchedCourse> searchedCourses = null;
int semesterNo = request.getParameter("semesterNo");
searchedCourses = //Using function to retrieve data from DB and return an ArrayList
String courses = gson.toJson(searchedCourses);
out.write(courses);
}
}
} finally {
out.close();
}
}
,這是返回JSON字符串「我用螢火蟲來複制」
[{"courseNumber":1619,"courseNo":"HADTA1100","courseName":"قرآن كريم (1) جزء عم","courseExamDate":"Aug 21, 2011","courseExamTimeFrom":"14:30","courseExamTimeTo":"15:30"},{"courseNumber":1663,"courseNo":"HADTB1100","courseName":"قرآن كريم (2) جزء تبارك","courseExamDate":"Aug 23, 2011","courseExamTimeFrom":"14:30","courseExamTimeTo":"15:30"}]
我使用下面的代碼在客戶端側
jQuery.ajax({
url: 'auth/json/AvailableCoursesGetter',
type: "GET" ,
dataType: "json",
data: {
'semesterNo': 20112
},
success: function(data) {
for (var i = 0, len = data.length; i < len; i++) {
document.write(data[i].courseNumber);
}
}
});
解析JSON串
它在Mozilla FireFox4上正常工作,但在Google Chrome和IE中它不顯示任何東西
有什麼幫助嗎?
可能是因爲courseNumber的不在引號中? – barfoon 2011-06-01 16:40:40
不需要在JSON中引號。 – Eli 2011-06-01 16:41:28
我正在使用GSON庫來生成此字符串 – wshurafa 2011-06-01 16:42:35