我在我的servlet中创建了JSON,并将Json发送回ajax调用。
我想在表格中显示员工列表。 请帮我从JSON中检索值。
由于
{
"First Name": "Last Name",
"EmployeeList": [
{
"Ram": "Kumar"
},
{
"Varun": "Kuamr"
}
]
}
以下是我的JSP COde。
$(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());
}
}
答案 0 :(得分:0)
IMO你的json结构不正确:
{
"EmployeeList": [
{
"name" : "Ram",
"surname" : "Kumar"
},
{
"name" : "Varun",
"surname" : "Kuamr"
}
]
}
在此之后,您可以定期读取/写入json对象: