2012-09-13 36 views
12

Chỉ cần không nhận được nó những gì tôi đang làm sai .. Tôi đã tìm hàng chục câu hỏi tương tự, nhưng vẫn có sự hiểu lầm ... khi tôi gọi chức năng CallHandler từ JS, tôi luôn nhận được thông báo 'Yêu cầu không thành công'. hãy giúp tôi.vượt qua jquery json vào asp.net httphandler

JS/JQuery:

function CallHandler() { 
    $.ajax({ 
     url: "DemoHandler.ashx", 
     contentType: "application/json; charset=utf-8", 
     type: 'POST', 
     dataType: "json", 
     data: [{"id": "10000", "name": "bill"},{"id": "10005", "name": "paul"}], 
     success: OnComplete, 
     error: OnFail 
    }); 
    return false; 
} 

function OnComplete(result) { 
    alert(result); 
} 
function OnFail(result) { 
    alert('Request Failed'); 
} 

asp.net C# mã sau:

public void ProcessRequest(HttpContext context) 
{ 
    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); 
    string jsonString = HttpContext.Current.Request.Form["json"]; 

    List<Employee> emplList = new List<Employee>(); 
    emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString); 

    string resp = ""; 
    foreach (Employee emp in emplList){ 
    resp += emp.name + " \\ "; 
    } 
    context.Response.Write(resp); 
} 

public class Employee 
{ 
    public string id { get; set; } 
    public string name { get; set; } 
} 

Trả lời

24

Hãy thử

data: JSON.stringify([{id: "10000", name: "bill"},{id: "10005", name: "paul"}]) 

chỉnh sửa tôi loại bỏ các trích dẫn từ các tên thuộc tính

Ngoài ra, chuỗi JSON cần được đọc in other way

string jsonString = String.Empty; 

HttpContext.Current.Request.InputStream.Position = 0; 
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream)) 
{ 
    jsonString = inputStream.ReadToEnd(); 
} 

Một lao động giải pháp

public void ProcessRequest(HttpContext context) 
{ 
    var jsonSerializer = new JavaScriptSerializer(); 
    var jsonString = String.Empty; 

    context.Request.InputStream.Position = 0; 
    using (var inputStream = new StreamReader(context.Request.InputStream)) 
    { 
     jsonString = inputStream.ReadToEnd(); 
    } 

    var emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString); 
    var resp = String.Empty; 

    foreach (var emp in emplList) 
    { 
     resp += emp.name + " \\ "; 
    } 

    context.Response.ContentType = "application/json"; 
    context.Response.ContentEncoding = Encoding.UTF8; 
    context.Response.Write(jsonSerializer.Serialize(resp)); 
} 

public class Employee 
{ 
    public string id { get; set; } 
    public string name { get; set; } 
} 

public bool IsReusable 
{ 
    get 
    { 
     return false; 
    } 
} 
+0

ty, tôi đã thay đổi mã như Bạn được đăng, nhưng vẫn chỉ có "yêu cầu không" tỉnh táo. – ailmcm

+0

Tôi đã thêm một giải pháp làm việc –

+1

CẢM ƠN QUÝ VỊ! Bạn đã cứu ngày của tôi! nó hoạt động tốt ngay bây giờ. – ailmcm

Các vấn đề liên quan