Ajax请求返回空,抛出错误

时间:2012-08-21 14:54:31

标签: c# ajax json handler

我正在调用一个返回json对象的处理程序,但是响应导致$.ajax()调用没有responseText就命中了错误函数。处理程序response.ContentType是application / json。

ajax电话......

$.ajax({
    url: "http://localhost/_tools/ajax/getInstagramObject.ashx",
    type: 'GET',
    dataType: 'json',
    success: function (msg) {
        alert(msg.length);
    },
    error: function (e) {
        alert(e.responseText);
    }
});

这是处理程序返回的json

{"info":[{"userName":"jamie_cahs","id":"42763829","name":"Jamie Rose","data":[{"images":{"lowResolution":{"url":"http://distilleryimage4.s3.amazonaws.com/de9c1e74bf4511e1abd612313810100a_6.jpg","width":306,"height":306},"thumbnail":{"url":"http://distilleryimage4.s3.amazonaws.com/de9c1e74bf4511e1abd612313810100a_5.jpg","width":150,"height":150},"standardResolution":{"url":"http://distilleryimage4.s3.amazonaws.com/de9c1e74bf4511e1abd612313810100a_7.jpg","width":612,"height":612}},"caption":{"text":"#boston"},"link":"http://instagr.am/p/MUsh6dO9ls/"}]}

和处理程序......

public void ProcessRequest(HttpContext context) {
    HttpResponse httpResponse = context.Response;
    httpResponse.ContentType = "application/json";

    var json = new JsonWrapper();

    var users = from user in _instagramPromotionUsersDataContext.instagramPromotionUsers
                select user;

    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    foreach (var user in users) {
        HttpWebRequest instagramWebRequest = (HttpWebRequest)WebRequest.Create(string.Format(INSTAGRAM_ENDPOINT, user.id.ToString()));
        instagramWebRequest.Method = WebRequestMethods.Http.Get;
        instagramWebRequest.ContentType = "application/json; charset=utf-8";

        try {
            using(HttpWebResponse instagramWebResponse = (HttpWebResponse) instagramWebRequest.GetResponse()) {
                var dataContractJsonSerializer = new DataContractJsonSerializer(typeof (InstagramObject));
                InstagramObject instagramObject = (InstagramObject) dataContractJsonSerializer.ReadObject(instagramWebResponse.GetResponseStream());

                json.info.Add(new Dictionary<string, object>() {
                    {"userName", user.userName},
                    {"id", user.id.ToString()},
                    {"name", user.name},
                    {"data", instagramObject.data}
                });

            }
        } catch (WebException e) {
            //do nothing just go to next record if exception is thrown
        }
    }

    httpResponse.Write(javaScriptSerializer.Serialize(json));
}

1 个答案:

答案 0 :(得分:0)

ajax选项需要contentType,我从网址中删除了协议和主机。

$.ajax()更改为此...

$.ajax({
    url: "/_tools/ajax/getInstagramObject.ashx",
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {
        /*if (msg) {
        $('#test').text(msg);
        }*/
        alert(msg.length);
    },
    error: function (e) {
        alert(e.responseText);
    }
});