0

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));
}
4

1 に答える 1

0

ajax オプションには contentType が必要で、URL からプロトコルとホストを削除しました。

これに変更$.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);
    }
});
于 2012-08-21T17:44:42.683 に答える