2017-07-16 239 views
-1

我試圖從使用angularjs和c#的數據庫中獲取數據。 數據是好的,直到Response.Write在tasks.aspx.cs我從中得到的json,但console.log($ scope.data)打印一個html代碼。

Angularjs:

<script> 
      var app = angular.module('app', []) 
       .controller('mainController', 
        function ($scope, $http,$timeout) { 
         angular.element(document) 
          .ready(function() { 
           $http.get('../tasks.aspx?tp=getInitData') 
            .then(
             function (d) { 
              if (d.data == "error" || d.data == "") { 
               // 
              } else { 
               $scope.data = d.data; 
               console.log($scope.data); 
              } 
             }, 
             function (d) { 
              // 
             }); 
          }); 

         $scope.msg = { 
          IsError: false, 
          Text: "" 
         } 
<script> 

Tasks.aspx.cs:響應

using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using Newtonsoft.Json; 

    public partial class Tasks : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (Request["tp"] == null) Response.End(); 
      var tp = Request["tp"] as string; 
      var postData = new System.IO.StreamReader(Request.InputStream).ReadToEnd(); 
      dynamic obj = postData == "" ? null : JObject.Parse(postData); 
      //int id; 
      switch (tp) 
      { 
       case "ping": 
        Response.Write("ok"); 
        break; 
       case "getInitData": 
        String s = Utils.GetData(); 
        Response.Write(Utils.GetData()); 
        break; 
      } 
     } 
    } 
+0

我想有一個錯誤,你得到一個400或401或500(或其他)的HTML響應。查看數據並實際閱讀HTML。同時調試您的服務。 – Crowcoder

+0

'console.log(d);'show? – mjwills

回答

1

設置的contentType爲 「appliation.json」

Response.Clear(); 
Response.ContentType = "application/json; charset=utf-8"; 
Response.Write(JsonConvert.SerializeObject(Utils.GetData())); 
Response.End(); 
+0

Angular js($ http.get)默認使用'application/json'標頭。 – Crowcoder

0

感謝您答案,我有Rsponse.redirect在Tasks.aspx.cs的底部,我沒有注意到,所以現在一切正常。 再次感謝你。