ajax dopost,javascript - Pass json data to servlet (doPost) with Jquery $.ajax - Stack Overflow

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.

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值