i'm learning about calls to ajax so i'm trying to get the value of ('#abcd') (a html select). I'm using this line:
abcdVal = combo.options[combo.selectedIndex].value
When this value change i must store his value in a var like abcdVal for pass to servlet with:
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);
}});
});
i got the value and put in response as a text plain, but in html page i see:
[{"text":null,"value":10}]
Instead of [{"text":(selected value of html select),"value":10}]
i doing something wrong then i pass the data to servlet. how must i pass this var correctly?
My code
Javascript code
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('' + value.text + '');
});
},
error:function(){
//if there is an error append a 'none available' option
j('#abcd').html('none available');
}
});
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);
}});
});
})
Servlet code
@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.
}
8284

被折叠的 条评论
为什么被折叠?



