Here is my calculatioform.jsp which accept two number.
当我按下提交按钮时,它将使用ajax和jquery在同一个calculateFrom.jsp中显示包含加法,减法,乘法和除法的结果。
我用来获取响应的jquery和ajax是。
<script type="text/javascript" >
$(document).ready(function(){
$(".button").click(function() {
var str = $("form").serialize();
var str = $("form").serialize();
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
var msg = data.val1 + " + " + data.val2 + " = " + data.sum;
alert(msg);
}
});
return false;
This is my calulator.jsp page on clicking submit button the request go to this
页面。它将从表格中取两个参数并进行计算。输入值为 存储在Val1和Val2中。基于此我计算结果。
String result = "({";
result += " val1 : " + val1 + ",";
result += " val2 : " + val2 + ",";
result += " sum : " + (val1 + val2) + ",";
但是这段代码不起作用。我需要做什么才能使代码正常工作。
答案 0 :(得分:4)
您没有在成功回调函数定义中定义data
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
success: function(data) { //you need data defined
根据返回的数据,您可能需要使用dataType
选项指定返回类型
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
//access properties through data
var msg = data.val1 + " + " + data.val2 + " = " + data.sum + '\n';
其他修改
此外,您似乎已将click事件附加到提交按钮,这可能导致脚本提交到自身或您在action
属性中设置的任何页面,您需要让它取消默认值使用preventDefault
$(".button").click(function(e) { //e will hold the event object
e.preventDefault() //prevents the default action of the event,
//in this case the form submission
var str = $("form").serialize();
您可能也会收到解析错误,也可以设置错误回调
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
dataType:"json",
success: function(data) {
var msg = data.val1 + " + " + data.val2 + " = " + data.sum;
alert(msg);
},
error:function(xhr,errormsg) {
alert(errormsg);
}
});
答案 1 :(得分:1)
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
var marks1=$("#marks1").val();
var marks2=$("#marks2").val();
var option=$("input:radio:checked").val();
var str = $("form").serialize();
$.ajax({
type: 'GET',
url: 'Operation',
data:{ marks1:marks1,
marks2:marks2,
option:option
},
success: function(data){
//Do something
}
});
});
});
答案 2 :(得分:0)
您可以通过网络方式获得回复
$(function(){
$(".button").click(function() {
var str = $("form").serialize();
$.ajax({
type: "GET",
url: "calculator.jsp",
data: str,
cache:false,
success: function(response) {
}
});
});