使用 Jquery $.ajax 将 json 数据传递给 servlet (doPost)
Pass json data to servlet (doPost) with Jquery $.ajax
我正在了解对 ajax 的调用,因此我正在尝试获取 ('#abcd') (a html select) 的值。我正在使用这条线:
abcdVal = combo.options[combo.selectedIndex].value
当这个值改变时,我必须将他的值存储在像 abcdVal 这样的 var 中,以便传递给 servlet:
var data = {"text" : abcdVal};
j("#mybutton").click(function(){
j.ajax({method: 'POST',
url: "/bin/company/repo",
dataType: 'JSON',
data: data,
success:function(result){
alert(result);
j("#demo").html('');
j('#demo').html(result);
}});
});
我得到了值并以纯文本形式响应,但在 html 页面中我看到:
[{"text":null,"value":10}]
而不是 [{"text":(selected 值 html select),"value":10}]
我做错了什么然后我将数据传递给 servlet。我必须如何正确传递此变量?
我的代码
Javascript代码
<script type="text/javascript">
var j = jQuery.noConflict();
var abcdVal;
j(document).ready(function(){
//get a reference to the select element
//request the JSON data and parse into the select element
j.ajax({
url: '/bin/company/repo',
dataType:'JSON',
success:function(data){
//clear the current content of the select
j('#abcd').html('');
//iterate over the data and append a select option
jQuery.each(data, function(text, value){
j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>');
});
},
error:function(){
//if there is an error append a 'none available' option
j('#abcd').html('<option id="-1">none available</option>');
}
});
j("#abcd").change(function(){
var combo = document.getElementById('abcd');
if(combo.selectedIndex<0)
alert('No hay opcion seleccionada');
else
abcdVal = combo.options[combo.selectedIndex].value;
alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value);
});
var data = {"text" : abcdVal};
alert(data);
j("#mybutton").click(function(){
j.ajax({method: 'POST',
url: "/bin/company/repo",
dataType: 'JSON',
data: data,
success:function(result){
alert(result);
j("#demo").html('');
j('#demo').html(result);
}});
});
})
</script>
Servlet 代码
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
IOException {
String text = (String) request.getParameter("text");
response.setHeader("Content-Type", "text/html; charset=UTF-8");
StringWriter writer = new StringWriter();
TidyJSONWriter json = new TidyJSONWriter(writer);
try
{
json.array();
//loop through your options and create objects as shown below
json.object();
json.key("text");
json.value(text);
json.key("value");
json.value(10);
json.endObject();
//end your array
json.endArray();
} catch(JSONException e) {
e.printStackTrace();
}
response.getWriter().write(writer.toString()); // Write response body.
}
使用 .live() 代替 .change() 因为您 select 元素是动态的。
j("#abcd").live('change', function(){
var combo = document.getElementById('abcd');
if(combo.selectedIndex<0)
alert('No hay opcion seleccionada');
else
abcdVal = combo.options[combo.selectedIndex].value;
alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value);
});
你能检查 chrome 网络面板中的 servlet 调用并检查 Request-Header and/or 表单数据吗?
不确定 javascript 中的问题,但如果您在 servlet 中遇到 NPE,那可能是因为您没有将其作为表单数据发布并尝试从请求参数中检索它。
访问作为请求负载发送的数据与访问表单数据略有不同。
如果您发现将 JSON 作为 请求负载 .
发布到 servlet,以下代码片段可能会对您有所帮助
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String requestData = buffer.toString();
//TODO: Retrieve required fields from this requestData string .
我做了这些更改来解决我的问题:
1) In ajax call change method: POST by type: 'POST'.
2) Add even.preventDefault() before call to ajax for dont use submit by default.
3) Change the form i handled data request. If i dont pass a form i need do this for retrieve request parameter like @Sabya explain.
4) Handle json inside of success (ajax) for show selection of html select.
所以代码是下一个:
JavaScript
<script type="text/javascript">
var j = jQuery.noConflict();
var abcd = document.getElementById("abcd");
var selection = abcd.options[abcd.selectedIndex].value
j(document).ready(function(){
j.ajax({
url: '/bin/company/repo',
dataType:'JSON',
success:function(data){
jQuery.each(data, function(text, value){
j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>');
});
},
error:function(){
//if there is an error append a 'none available' option
j('#abcd').html('<option id="-1">none available</option>');
}
});
j("#abcd").live('change',function(){
var combo = document.getElementById('abcd');
if(combo.selectedIndex<0)
alert('no option selected');
else
selection = combo.options[combo.selectedIndex].value;
});
j('form').on('submit', function(e){
event.preventDefault();
j.ajax({type: 'POST',
contentType: "application/json; charset=utf-8",
url: "/bin/company/repo",
dataType: 'JSON',
data: JSON.stringify({ "text": selection }),
success:function(data){
jQuery.each(data, function(text, value){
j('#demo').html('');
j('#demo').html(value.text);
});
}});
});
})
</script>
Servlet
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
IOException {
response.setHeader("Content-Type", "application/json");
PrintWriter out = response.getWriter();
StringWriter writer = new StringWriter();
TidyJSONWriter json = new TidyJSONWriter(writer);
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
try
{
JSONObject jsonObj = new JSONObject(new String(data));
json.array();
//loop through your options and create objects as shown below
json.object();
json.key("text");
json.value(jsonObj.get("text"));
json.endObject();
//end your array
json.endArray();
} catch(JSONException e) {
e.printStackTrace();
}
out.write(writer.toString());
}
我正在了解对 ajax 的调用,因此我正在尝试获取 ('#abcd') (a html select) 的值。我正在使用这条线:
abcdVal = combo.options[combo.selectedIndex].value
当这个值改变时,我必须将他的值存储在像 abcdVal 这样的 var 中,以便传递给 servlet:
var data = {"text" : abcdVal};
j("#mybutton").click(function(){
j.ajax({method: 'POST',
url: "/bin/company/repo",
dataType: 'JSON',
data: data,
success:function(result){
alert(result);
j("#demo").html('');
j('#demo').html(result);
}});
});
我得到了值并以纯文本形式响应,但在 html 页面中我看到:
[{"text":null,"value":10}]
而不是 [{"text":(selected 值 html select),"value":10}]
我做错了什么然后我将数据传递给 servlet。我必须如何正确传递此变量?
我的代码
Javascript代码
<script type="text/javascript">
var j = jQuery.noConflict();
var abcdVal;
j(document).ready(function(){
//get a reference to the select element
//request the JSON data and parse into the select element
j.ajax({
url: '/bin/company/repo',
dataType:'JSON',
success:function(data){
//clear the current content of the select
j('#abcd').html('');
//iterate over the data and append a select option
jQuery.each(data, function(text, value){
j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>');
});
},
error:function(){
//if there is an error append a 'none available' option
j('#abcd').html('<option id="-1">none available</option>');
}
});
j("#abcd").change(function(){
var combo = document.getElementById('abcd');
if(combo.selectedIndex<0)
alert('No hay opcion seleccionada');
else
abcdVal = combo.options[combo.selectedIndex].value;
alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value);
});
var data = {"text" : abcdVal};
alert(data);
j("#mybutton").click(function(){
j.ajax({method: 'POST',
url: "/bin/company/repo",
dataType: 'JSON',
data: data,
success:function(result){
alert(result);
j("#demo").html('');
j('#demo').html(result);
}});
});
})
</script>
Servlet 代码
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
IOException {
String text = (String) request.getParameter("text");
response.setHeader("Content-Type", "text/html; charset=UTF-8");
StringWriter writer = new StringWriter();
TidyJSONWriter json = new TidyJSONWriter(writer);
try
{
json.array();
//loop through your options and create objects as shown below
json.object();
json.key("text");
json.value(text);
json.key("value");
json.value(10);
json.endObject();
//end your array
json.endArray();
} catch(JSONException e) {
e.printStackTrace();
}
response.getWriter().write(writer.toString()); // Write response body.
}
使用 .live() 代替 .change() 因为您 select 元素是动态的。
j("#abcd").live('change', function(){
var combo = document.getElementById('abcd');
if(combo.selectedIndex<0)
alert('No hay opcion seleccionada');
else
abcdVal = combo.options[combo.selectedIndex].value;
alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value);
});
你能检查 chrome 网络面板中的 servlet 调用并检查 Request-Header and/or 表单数据吗?
不确定 javascript 中的问题,但如果您在 servlet 中遇到 NPE,那可能是因为您没有将其作为表单数据发布并尝试从请求参数中检索它。
访问作为请求负载发送的数据与访问表单数据略有不同。
如果您发现将 JSON 作为 请求负载 .
发布到 servlet,以下代码片段可能会对您有所帮助 BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String requestData = buffer.toString();
//TODO: Retrieve required fields from this requestData string .
我做了这些更改来解决我的问题:
1) In ajax call change method: POST by type: 'POST'.
2) Add even.preventDefault() before call to ajax for dont use submit by default.
3) Change the form i handled data request. If i dont pass a form i need do this for retrieve request parameter like @Sabya explain.
4) Handle json inside of success (ajax) for show selection of html select.
所以代码是下一个:
JavaScript
<script type="text/javascript">
var j = jQuery.noConflict();
var abcd = document.getElementById("abcd");
var selection = abcd.options[abcd.selectedIndex].value
j(document).ready(function(){
j.ajax({
url: '/bin/company/repo',
dataType:'JSON',
success:function(data){
jQuery.each(data, function(text, value){
j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>');
});
},
error:function(){
//if there is an error append a 'none available' option
j('#abcd').html('<option id="-1">none available</option>');
}
});
j("#abcd").live('change',function(){
var combo = document.getElementById('abcd');
if(combo.selectedIndex<0)
alert('no option selected');
else
selection = combo.options[combo.selectedIndex].value;
});
j('form').on('submit', function(e){
event.preventDefault();
j.ajax({type: 'POST',
contentType: "application/json; charset=utf-8",
url: "/bin/company/repo",
dataType: 'JSON',
data: JSON.stringify({ "text": selection }),
success:function(data){
jQuery.each(data, function(text, value){
j('#demo').html('');
j('#demo').html(value.text);
});
}});
});
})
</script>
Servlet
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException,
IOException {
response.setHeader("Content-Type", "application/json");
PrintWriter out = response.getWriter();
StringWriter writer = new StringWriter();
TidyJSONWriter json = new TidyJSONWriter(writer);
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
try
{
JSONObject jsonObj = new JSONObject(new String(data));
json.array();
//loop through your options and create objects as shown below
json.object();
json.key("text");
json.value(jsonObj.get("text"));
json.endObject();
//end your array
json.endArray();
} catch(JSONException e) {
e.printStackTrace();
}
out.write(writer.toString());
}