我正在使用这段代码来访问我的服务器(MVC),这样就可以很好地工作。在结果"data“( {"Id":30,"Description":"Samples Photos","Name":"First Galery"})中,我尝试获取属性data.Name,结果什么也没有返回,这段代码有什么问题?
JavaScript
$(function () {
$('#UserGaleries_').change(function () {
try {
if ($(this).val() == -1) {
$('#NameGaleriesEdit').val('');
$('#DescriptionGaleriesEdit').val('');
}
else {
$.post('/UserGaleries/ChangeCategorie',
{ selectedID: $(this).val() },
function (data) {
alert(data.Name); //Nothing
$('#NameGaleriesEdit').val(data.name);
$('#DescriptionGaleriesEdit').val('asdf');
});
}
} catch (e) {
alert(e);
}
});
});MVC
[Serializable]
public class ResponsetModel
{
public int Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
}
public JsonResult ChangeCategorie(int selectedID)
{
DbLayer.UserGaleriesManager uc = new DbLayer.UserGaleriesManager();
DbLayer.Models.UsersGalery cat = uc.GetGaleriesById(selectedID);
ResponsetModel retValue = new ResponsetModel()
{ Id = cat.Id, Name = cat.Title, Description = cat.Description };
JsonResult oView = Json(retValue, "text/plain", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
return oView;
}发布于 2012-02-20 04:47:02
当您在没有指定预期内容类型的情况下使用post()方法时,data将只是一个包含JSON的字符串(而不是JavaScript对象)。执行alert(data)以验证这一点。
将该帖子重写为
$.ajax({
url:'/UserGaleries/ChangeCategorie',
data:{ selectedID: $(this).val() },
method:"POST",
dataType:"json",
success:function (data) {
alert(data.Name);
}
});或者你也可以使用$.getJSON(),但我不确定你是否能让它执行POST请求。
发布于 2012-02-20 04:47:06
您可以尝试将$.post( )中的dataType设置为"json“吗?查看文档中的示例。1
它也是data.Name而不是data.name。
如下所示:
$.post('/UserGaleries/ChangeCategorie',
{ selectedID: $(this).val() },
function (data) {
alert(data.Name);
$('#NameGaleriesEdit').val(data.Name);
$('#DescriptionGaleriesEdit').val('asdf');
}, "json");重要建议:使用Firebug检查来自应用程序服务器的确切响应。
发布于 2012-02-20 04:57:32
您还可以在使用JSON.parse(result)返回JSON数据之后对其进行解析。
https://stackoverflow.com/questions/9352936
复制相似问题