如何解决ajax接收的值的问题
最近在一直使用AJAX来实现局部刷新,但是突然发现AJAX接收后台的信息全是未定义,然后最近才发现要想在前台页面获取到改变类型的值,需要进行Json数据转换。
$(".btnfb").each(function () {
$(this).click(function () {
var _this = $(this);
$.ajax({
url: "/ZH_SY/Save",
type: "GET",
data: { "text": $(this).prev().find("input[type='text']").val(), "HDId": $(this).next().text() },
contentType: "application/json;charset=utf-8",
success: function (result) {
if (result != null) {
var rt = result;
_this.parent().prev().html(rt.content);
_this.prev().find("input").val("");
_this.parent().prev().prev().find("div").text(rt.number + "条评论");
} else {
alert('添加失败');
}
},
error: function (err) {
alert("出现错误" + err);
}
})
})
})
这是一段通过AJAX传值从后台读取HTML页面代码然后显示的功能实现,为了实现用户评论之后在不刷新页面的情况下,将数据展示上去。前端页面传过来了两个值,一个是用户的评论循环代码,一个是用户评论的数量,但是在进行读值的时候一直获取不到,一直显示是undifinded数据,然后才知道后台传值的时候没有进行类型转换。
后台代码:
public object Save(string text,string HDId)
{
string tt = Session["UserID"].ToString() ;
db.PingLun.Add(new PingLun()
{
HDId = Convert.ToInt32(HDId),
UserID = Convert.ToInt32(Session["UserID"]),
PLContent = text,
PLRiqi = DateTime.Now
});
foreach (HuiDa item in db.HuiDa.ToList())
{
if (item.HDId == Convert.ToInt32(HDId))
{
item.HDPingLun = item.HDPingLun + 1;
break;
}
}
db.SaveChanges();
string message = "";
foreach (PingLun item in db.PingLun.ToList().Where(n => n.HDId == Convert.ToInt32(HDId)))
{
Users us = db.Users.Where(pu => pu.Id == item.UserID).First();
if (DateTime.Now.Year - Convert.ToDateTime(item.PLRiqi).Year != 0)
{
message += "<div style='width: 100%;border-bottom: 1px solid #f6f6f6;margin-top: 8px;'>" +
"<div class='grid' style='height: 24px;'>" +
"<i style='width: 24px;height: 24px;margin-left: 12px;margin-right: 4px;'><img src='/img/"+us.Timg+"' width='24px' height='24px' /></i>" +
"<div class='grid-cell-10'>"+us.Name+"</div>" +
"<div class='grid-cell-2' style='font-size:13.5px;color: #8590a6;'>"+Convert.ToDateTime(item.PLRiqi).ToShortDateString().ToString()+"</div>" +
"</div>" +
"<div style='margin: 10px 28px 10px 36px;'>"+item.PLContent+"</div>" +
"</div>";
}
else
{
message += "<div style='width: 100%;border-bottom: 1px solid #f6f6f6;margin-top: 8px;'>" +
"<div class='grid' style='height: 24px;'>" +
"<i style='width: 24px;height: 24px;margin-left: 12px;margin-right: 4px;'><img src='/img/"+us.Timg+"' width='24px' height='24px' /></i>" +
"<div class='grid-cell-10'>"+us.Name+"</div>" +
"<div class='grid-cell-2' style='font-size:13.5px;color: #8590a6;'>"+Convert.ToDateTime(item.PLRiqi).GetDateTimeFormats('M')[0].ToString()+"</div>" +
"</div>" +
"<div style='margin: 10px 28px 10px 36px;'>"+item.PLContent+"</div>" +
"</div>";
}
}
int num = Convert.ToInt32(HDId);
object ct = new
{
content = message,
number = db.HuiDa.First(p => p.HDId == num).HDPingLun
};
return Json(ct,JsonRequestBehavior.AllowGet);
}
之前的返回值是
object ct = new
{
content = message,
number = db.HuiDa.First(p => p.HDId == num).HDPingLun
};
return ct;
所以才一直读不到值,最后经过询问老师才知道是需要进行数据转换。