JQuery AJAX响应仅在C#ASP.NET中返回[object Object]和Undefined

时间:2015-05-05 11:24:42

标签: jquery asp.net ajax json

我已经多次询问过这个问题,但请尽量了解我的实际问题。

我的JavaScript代码是:

     $.ajax({
            type: "POST",
            url: 'ScheduleCampiagn.aspx/GetTemplate',
            data: '{TempId: ' + $('#<%=ddl_Select_Template.ClientID%>').val() + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response);
            },
            failure: function (response) {

            }
        });

我在ScheduleCampiagn.aspx.cs中的GetTemplate函数是:

[System.Web.Services.WebMethod]
public static List<TemplateClass> GetTemplate(int TempId)
{
    List<TemplateClass> dataTemp = new List<TemplateClass>();
    TemplateClass temp = new TemplateClass();
    String cmd = "Select Tmpl_Id,Tmpl_Body_Content from TBL_DESIGN_TEMPLETE WHERE Tmpl_Id='" + TempId + "'";
    DataSet dsTemp = new DataSet();
    dsTemp.Clear();
    con.Retrive(cmd, ref dsTemp);
    cmd = string.Empty;
    temp.TempId = Convert.ToInt32(dsTemp.Tables[0].Rows[0]["Tmpl_Id"]);
    temp.TempContent = Convert.ToString(dsTemp.Tables[0].Rows[0]["Tmpl_Body_Content"]);
    dataTemp.Add(temp);
    return dataTemp;
}

GetTemplate函数只返回我预期的一行。但我的问题是:

1.当它执行显示内容为[对象对象]的警告框时。

2.当我将成功功能更改为             警报(响应[0] .TempId);         它表明响应是不可取的

3.i还使用FireBug调试js代码它显示了ReferenceError:响应未定。

4.i也尝试使用response.d来获取值,但它无效。

我只想获取dataTemp的内容:e

        1.dataTemp.TempId

        2.dataTemp.TempContent

请帮助我,或者请告诉我这些代码中遗漏的内容,我已经通过搜索丢失了整整一天。

非常感谢

1 个答案:

答案 0 :(得分:3)

响应包含在d属性中。

$.ajax({
            type: "POST",
            url: 'ScheduleCampiagn.aspx/GetTemplate',
            data: '{TempId: ' + $('#<%=ddl_Select_Template.ClientID%>').val() + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                // fail-safe for older ASP.NET frameworks
                var data = response.hasOwnProperty("d") ? response.d : response;
                alert(data.TempId);  //Changed here
            },
            failure: function (response) {

            }
        });

代码隐藏方法。

//Changed the return type to a single object instead of list.
[System.Web.Services.WebMethod]
public static TemplateClass GetTemplate(int TempId)
{

    TemplateClass temp = new TemplateClass();
    String cmd = "Select Tmpl_Id,Tmpl_Body_Content from TBL_DESIGN_TEMPLETE WHERE Tmpl_Id='" + TempId + "'";
    DataSet dsTemp = new DataSet();
    dsTemp.Clear();
    con.Retrive(cmd, ref dsTemp);
    cmd = string.Empty;
    temp.TempId = Convert.ToInt32(dsTemp.Tables[0].Rows[0]["Tmpl_Id"]);
    temp.TempContent = Convert.ToString(dsTemp.Tables[0].Rows[0]["Tmpl_Body_Content"]);

    return temp;
}