2016-03-07 58 views
1

這是我的POST請求追加對象:角響應末

$scope.TestPost = function (par1, par2) { 

       $http.post('EmployeeService.asmx/GetAllEmployees', 
        {      
         par1: par1, 
         par2: par2  
       }) 
       .then(function (response) { 
        $scope.employees = response.data; 
       }) 
      }; 

這是被調用服務器端代碼。代碼正確調用和JSON序列化對象寫入響應:

[WebMethod] 
public void GetAllEmployees(string par1, string par2) 
{ 
    List<Employee> listEmployees = new List<Employee>(); 
    string cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString; 
    using(SqlConnection con = new SqlConnection(cs)) 
    { 
     List<Employee> _list = new List<Employee>(); 
     SqlCommand cmd = new SqlCommand("SELECT * FROM tblEmployees", con); 
     con.Open(); 
     SqlDataReader rdr = cmd.ExecuteReader(); 
     while(rdr.Read()) 
     { 
      Employee emp = new Employee 
      { 
       id = Convert.ToInt32(rdr["Id"]), 
       name = rdr["Name"].ToString(), 
       gender = rdr["Gender"].ToString(), 
       salary = Convert.ToInt32(rdr["Salary"]) 
      }; 
      listEmployees.Add(emp); 
     } 
    } 

    JavaScriptSerializer js = new JavaScriptSerializer();    
    Context.Response.Write(js.Serialize(listEmployees)); 
} 

Response對象是這樣的 - 一些奇怪的行結尾處附加{「d」:空}我不明白爲什麼。我也收到錯誤在客戶端:語法錯誤:意外的令牌:

"[{"id":1,"name":"Ben","gender":"Male","salary":55000}, 
{"id":2,"name":"Sara","gender":"Female","salary":68000}, 
{"id":3,"name":"Mark","gender":"Male","salary":57000}, 
{"id":4,"name":"Pam","gender":"Female","salary":53000}, 
{"id":5,"name":"Todd","gender":"Male","salary":60000}]{"d":null}" 
+1

這個問題不完整?你可以請包括從服務器端和客戶端console.logs輸出?謝謝 ! – 82Tuskers

+0

我遇到了非代碼問題。對於最後的JSON,SO給我錯誤的代碼沒有正確發佈。 – FrenkyB

+0

感謝您發佈日誌。多一點青睞。我需要這個變量的日誌:listEmployees。我認爲這個錯誤可能是你的SQL查詢的結果。 – 82Tuskers

回答

1

感謝@ 82Tuskers和這個職位: Differences between Response.End() and Response.Flush()

我已經找到了解決辦法。我已將服務器端功能末尾的代碼更改爲:

Context.Response.Clear(); 
Context.Response.Write(js.Serialize(listEmployees)); 
Context.Response.Flush(); 
Context.Response.End(); 

現在可以響應了。