我使用以下ajax代码将数据从表单提交到servlet,然后让servlet发回数据(还没有完全掌握这部分)。
附带问题,变量id是使用
从.jsp文件中获取的`<script> var id = '${id}' </script>`
有没有更好的方法直接从页面上加载的.js文件中访问此变量?它按原样工作,但看起来很乱。
$(document).ready(function () {
$('.doAction').click(function () {
var rel = parseInt($('.doAction:checked').attr('rel'));
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: {
rating: rel,
itemID: id
},
url: 'Ratings',
success: function (data) {
}
});
});
});
HTML表单代码是
<div id=holder>
<div id="rating">
Rating
<form id="ratingsform" name="ratingsform">
<input class="doAction" type="radio" name="ra1" rel="1" />
<input class="doAction" type="radio" name="ra1" rel="2" />
<input class="doAction" type="radio" name="ra1" rel="3" />
<input class="doAction" type="radio" name="ra1" rel="4" />
<input class="doAction" type="radio" name="ra1" rel="5" />
</form>
</div>
</div>
所以我想要发生的是当选择一个单选按钮时,表单被禁用,因此无法按下新的单选按钮(因此servlet不能被发送到死机)。当servlet响应ajax post call时,我想更改div“rating”的内容以显示更新的评级并删除投票能力,即删除单选按钮/表单。我有服务器端代码工作,除了弄清楚如何返回所需的值,希望非常直接。
有什么建议吗?
答案 0 :(得分:1)
请仔细检查我的评论以了解更改
$(document).ready(function () {
var id = '${id}' // you can have it here
$('.doAction').click(function () {
var rel = $('.doAction:checked').attr('rel'); // you need not parse to int because it will always string in parameter
$('.doAction').prop('disabled', true); // to disable radio button
$.ajax({
type: 'POST',
dataType: 'html', // change this since your servlet response is html not json
cache: false,
data: {
rating: rel,
itemID: id
},
url: 'Ratings',
success: function (data) {
$('#rating').html(data); // assuming response as {"rating" : 4.4}
}
});
});
});
答案 1 :(得分:0)
在服务器端脚本中,您需要print
要发回的数据,然后通过success
对象的$.ajax
函数调用它:
// Other AJAX...
success:function(msg){
$('#rating').html(msg);
}
// Other AJAX
我不是最熟悉的JSP,但我相信命令类似于out.print()
。
答案 2 :(得分:0)
//你的js
$(document).ready(function () {
$('.doAction').live('click',function () {
// If we click then it is checked
var rel = parseInt($(this).attr('rel'));
// The id of the input hidden
var id = $('#theID').val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: {
rating: rel,
itemID: id
},
url: 'Ratings',
success: function (data) {
// Displays the data returned by your servlet
$('#rating').html(data);
}
});
});
});
// HTML
<div id=holder>
<div id="rating">
Rating
<form id="ratingsform" name="ratingsform">
<input type="hidden" name="theID" value='${id}'/>
<input class="doAction" type="radio" name="ra1" rel="1" />
<input class="doAction" type="radio" name="ra1" rel="2" />
<input class="doAction" type="radio" name="ra1" rel="3" />
<input class="doAction" type="radio" name="ra1" rel="4" />
<input class="doAction" type="radio" name="ra1" rel="5" />
</form>
</div>
</div>
答案 3 :(得分:-1)
首先,服务器返回数据?这是怎么回事?我愿意:
...
success: function (data) {
$("#ratings").html('<div class="rating '+rel+'stars"></div>');
}
...
并创建2个类,一个名为rating
,另外五个名为1,2,3,4,5stars,这将有效。