Jquery getJSON函数没有提供警报

时间:2012-02-05 20:22:15

标签: jquery json

我有一个页面调用CustomerJASON.aspx,其代码类似于

protected void Page_Load(object sender, EventArgs e)
    {
        //MakeJasonCustomer();
        Request.ContentType = "application/json";
        var customer = new Customer()
        {
            ID = int.Parse(Request["id"]),
            FirstName = "Haseeb",
            LastName = "Khan"
        };
        var jsonSerializer = new DataContractJsonSerializer(typeof(Customer));
        jsonSerializer.WriteObject(Response.OutputStream, customer);
    }

我使用jQuery getjason函数调用此页面,我编写的代码是

$(document).ready(function () {
    LoadData();
});


function LoadData() {

    $('#SubmitButton').click(function () {

        $.getJSON('CustomerJASON.aspx', { id: 5 }, function (data) {
            alert(data.FirstName);

        });
    });

}

但问题是我无法从getJSON函数获取警报。请帮助我完全卡住。

3 个答案:

答案 0 :(得分:0)

尝试将console.log或console.dir添加到数据代码中以确保它实际上是一个对象,因为如果它没有警告它没有被调用或者data.firstName不正确并且javascript失败

console.dir(data);
alert(data.firstName);

检查firebug或其他工具正在显示的数据

答案 1 :(得分:0)

您可以在'CustomerJASON.aspx'中添加另一个WebMethod来处理返回值而不是Page Load事件

[System.Web.Services.WebMethod]
public static string LoadData() { //Code Here }

和Javascript代码:

$.getJSON('CustomerJASON.aspx/LoadData', { id: 5 }, function (data)

答案 2 :(得分:0)

如果ajax请求失败,

$.getJSON()什么都不做。打开开发者控制台(F12,网络标签)并检查回复。

或者,尝试附加错误处理程序以查看是否发生了什么。

$.getJSON('CustomerJASON.aspx', { id: 5 }, function (data) {
    alert(data.FirstName);
}).error(function(jqXHR, textStatus, errorThrown) {
    // Inspect the values of jqXHR, textStatus, errorThrown here.
});
相关问题