我正在學習有關調用ajax的知識,所以我試圖獲得('#abcd')(html選擇)的值。我用這條線:
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頁面中,我看到:
[{ 「文」:空, 「值」:10}]
相反[{ 「文本」 :(HTML的選擇值來選擇), 「值」: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.
}
也許代碼可以更乾淨,但這是一個解決方案 - @Sabya – jmhdez 2015-04-08 10:26:26