【发布时间】:2016-10-31 20:34:58
【问题描述】:
我在我的 servlet 中创建了 JSON 下面并将 Json 发送回 ajax 调用作为响应。
我想在表格中显示员工列表。 请帮我从 JSON 中检索值。
谢谢
{
"First Name": "Last Name",
"EmployeeList": [
{
"Ram": "Kumar"
},
{
"Varun": "Kuamr"
}
]
}
下面是我的 JSP 代码。
$(document).ready(function() {
$("#JsonStart").click(function(e) {
e.preventDefault();
alert("Hi");
$.ajax({
url: "/bin/getEmployee",
method: "GET",
success: function(myresponse) {
alert("Inside Ajax" + myresponse);
// $("#ajaxResponse").text(myresponse);
$("#ajaxResponse").html("");
$("#ajaxResponse").append("<b>My Ajax Response :</b>" + myresponse);
$.each(myresponse, function(key, value) {
alert("Value :" + value);
alert("Key :" + key);
});
console.log("success");
},
failure: function(myresponse) {
CQ.Notification.notifyFromResponse(myresponse);
}
});
});
});
<form>
<div>
<button type="button" id="JsonStart" name="Shareitem">TestJ</button>
</div>
</form>
<div id="anotherSection">
<fieldset>
<legend>Response from jQuery Ajax Request</legend>
<div id="ajaxResponse"></div>
</fieldset>
</div>
下面是我的 servlet 代码:
public class EmployeeInfoServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
JSONObject employeeJson = new JSONObject();
try {
employeeJson.put("EmployeeFirst", "Employee Last");
JSONArray empJsonArray = new JSONArray();
JSONObject Employee1=new JSONObject();
Employee1.put("Ram", "Kumar");
empJsonArray.put(Employee1);
JSONObject Employee2=new JSONObject();
Employee2.put("Varun", "Kuamr");
empJsonArray.put(Employee2);
employeeJson.put("EmployeeList", empJsonArray);
System.out.println("Employee JSON"+employeeJson.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(employeeJson.toString());
}
}
【问题讨论】:
-
不是在每个循环中遍历“myresponse”,而是遍历“myresponse.EmployeeList”,因为您知道在该键中只存储您的姓名。
标签: javascript java jquery json ajax