我明白這個問題的答案。我回復瞭如下所示的Content-Type:text/html
。
<textarea>{"ContentEncoding":null,"ContentType":null,"Data":{"prop1":1},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}</textarea>
用於讀取響應的客戶端代碼。
function (xhr)
{
try{
console.log(xhr.responseText);
var originalData = $(xhr.responseText);
var jsonResponse = $.parseJSON(originalData.html());
var propValResult = jsonResponse.Data.prop1;
}
catch (e)
{
};
}
以下是我創建包裝響應的服務器端代碼。
ASP.NET MVC自定義結果
public class JsonTextWrappedResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet)
&& string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Get Not Allowed");
}
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string results = "<textarea>" + serializer.Serialize(Data) + "</textarea>";
response.Write(results);
}
}
}
控制器代碼示例
public JsonTextWrappedResult PracticeInfoFormUpload(HttpPostedFileBase myfile, FormCollection formCollection)
{
var data = this.Json(
new
{
prop1 = 1
});
var result = new JsonTextWrappedResult { Data = data, ContentType = "text/html" };
return result;
}
哇,真快......不幸的是,這並不完全做的伎倆又:數據。 html()會產生TypeError:「data.html不是函數」。這並不令我感到意外,因爲數據似乎只是一個字符串。我錯過了什麼? – duffy 2010-11-05 18:55:39
我想我現在明白了。 「data = $ .parseJSON($(data).html());」似乎工作。 (我仍然對jQuery不熟悉,但我想它會從字符串中創建一個dom元素?)感謝您的幫助! – duffy 2010-11-05 19:07:12