[英]AJAX is not receiving data on success, it shows the result as "undefined"
This is jQuery code snippet is not getting valid data through AJAX and keeps updating data in divs as undefined
.这是 jQuery 代码片段未通过 AJAX 获取有效数据,并不断将 div 中的数据更新为
undefined
。 I don't know what the problem is.我不知道是什么问题。
function success(data) {
alert(data.amount);
$('#summary').html(data.count + "|" + data.amount);
};
$(document).ready(function () {
$("#button1").click(function (evt) {
evt.preventDefault();
var $form = $("#form1");
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
tradition: true,
success: function(data) {
success(data);
}
});
});
});
If I modify following success function to simply load a new page that shows the correct results that Action returns如果我修改以下成功函数以简单地加载一个新页面,该页面显示 Action 返回的正确结果
function success(data) {
$('#summary').html(data);
};
This is the controller action code snippet that receives the form fields data (id and quantity) from the view and returns count
and amount
:这是从视图接收表单字段数据(id 和数量)并返回
count
和amount
的控制器操作代码片段:
public JsonResult AddtoCartDt(string id,string quantity)
{
int id2 = int.Parse(id);
Product pro = Data.Products.Single(c => c.Id == id2);
var cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
int l = int.Parse(quantity);
for (int i = 0; i < l; i++)
{
cart.AddToCart(pro);
}
var Cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
cartSummary summ = new cartSummary()
{
amount = Cart.GetTotal(),
count = Cart.GetCount()
};
return Json(summ, JsonRequestBehavior.AllowGet);
}
Your code looks fine, but you should add some debug statements to check the response.您的代码看起来不错,但您应该添加一些调试语句来检查响应。
For starters, you could pass the success
method directly as your ajax
success
handler, and add an error handler to log out any error:对于初学者,您可以直接将
success
方法作为ajax
success
处理程序传递,并添加一个错误处理程序以注销任何错误:
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
traditional: true,
// no need for the function()...
success: success,
error: console.log
});
// Alternatively, you could chain it:
$.ajax(/*...*/).done(success).fail(console.log);
That will call pass the JSON
response as your success
method parameter.这将调用传递
JSON
响应作为您的success
方法参数。
Then, try to add a console.log()
statement to debug the response in the console:然后,尝试添加一个
console.log()
语句来调试控制台中的响应:
function success(data) {
console.log(data);
$('#summary').html(data.count + "|" + data.amount);
};
Edit编辑
Check the tradition
parameters in your ajax
call.检查
ajax
调用中的tradition
参数。 In the doc it's called traditional
.在文档中它被称为
traditional
。 Also, check the route name
and http
method in your controler.另外,请检查控制器中的
route name
和http
方法。 You may want to add something like this in your controller:你可能想在你的控制器中添加这样的东西:
[Route("~/myroute"), HttpPost]
public JsonResult AddtoCartDt(string id,string quantity)
{
/*
*/
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.