$ http.get返回html代码而不是JSON
问题描述:
我试图从使用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;
}
}
}
答
设置的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
答
感谢您答案,我有Rsponse.redirect在Tasks.aspx.cs的底部,我没有注意到,所以现在一切正常。 再次感谢你。
我想有一个错误,你得到一个400或401或500(或其他)的HTML响应。查看数据并实际阅读HTML。同时调试您的服务。 – Crowcoder
'console.log(d);'show? – mjwills