1。請求text數據,在success事件中手動解析jquery
前臺:
$.ajax({
type: "post",
url: "checkFile.ashx",
data: { "filename": "2" },
dataType: "text",
success: function (data) {
var json = eval('(' + data + ')');
alert(json.Age);
}
});
後臺處理:
HttpResponse res = context.Response;
HttpRequest req = context.Request;
string code = req["filename"];
string jsonString = "{\"Age\":28,\"Name\":\"張三\"}";
//string jsonString = "{'Age':23,'Name':'abc'}";
if (code != null)
{
res.Write(jsonString);
res.ContentType = "text/plain";
res.End();
}
在這種狀況下,單引號分割和轉移雙引號分割,均可以。
2.請求json格式數據,jquery自動解析
前臺:
$.ajax({
type: "post",
url: "checkFile.ashx",
data: { "filename": "3" },
// contentType:"application/json",----------
在ajax請求ashx文件的json數據時,此屬性不能被指定,而在請求webservices時,是必須指定的。
dataType: "json",
success: function (data) {
alert(data.Name);
}
});
後臺處理:
HttpResponse res = context.Response;
HttpRequest req = context.Request;
string code = req["filename"];
string jsonString = "{\"Age\":28,\"Name\":\"張三\"}";
if (code != null)
{
res.Write(jsonString);
res.ContentType = "text/plain";
res.End();
}
在這種狀況下,只有轉移雙引號分割,才能夠在前臺被jquery方法自動解析。
3.帶序列化的text數據前臺解析
前臺:
$.ajax({
type: "post",
url: "checkFile.ashx",
data: { "filename": "2" },
dataType: "text",
success: function (data) {
$("p").text(data);
var json = eval('(' + data + ')');
alert(json.Name);
}
});
json數據內容: {"Name":"zhangsan","Code":111,"Birthday":"\/Date(649666800000)\/"}
後臺處理:
HttpResponse res = context.Response;
HttpRequest req = context.Request;
string code = req["filename"];
Student stu = new Student {
Name="zhangsan",
Code=111,
Birthday=Convert.ToDateTime("1990-8-3")
};
JavaScriptSerializer serializer=new JavaScriptSerializer();
string jsonString = serializer.Serialize(stu);
json數據內容: "{\"Name\":\"zhangsan\",\"Code\":111,\"Birthday\":\"\\/Date(649666800000)\\/\"}"
if (code != null)
{
res.Write(jsonString);
res.ContentType = "text/plain";
res.End();
}
[Serializable]
public class Student
{
public string Name { get; set; }
public int Code { get; set; }
public DateTime Birthday { get; set; }
}
4.帶序列化的json 前臺自動解析:
前臺:
$.ajax({
type: "post",
url: "checkFile.ashx",
data: { "filename": "3" },
dataType: "json",--------------只要指定此處就能夠,後臺處理同上。
success: function (data) {
alert(data.Name);
}
});