JavaScript运行时错误:字符无效

时间:2013-11-27 11:43:15

标签: c# javascript jquery asp.net ajax

我正在尝试从Ajax访问ASP.NET处理程序。我使用锚标记将数据传递给它并返回一些 test 字符串。以下是代码:

Ajax代码

function incvote(topicid) {
    $.ajax({
        type: "POST",
        url: "WCAccess.ashx",
        data: JSON.stringify({ "desid": "topicid" }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            return response.d;
        },
        error: function (xhr, ajaxOptions, thrownError) {

            alertify.error("Some error occured. Please try again.");
        },
        //async: true
    });

处理程序代码

public class WCAccess : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        string jsonString = string.Empty;
        List<ArgsVals> argsList = new List<ArgsVals>();
        context.Request.InputStream.Position = 0;
        using (var inputStream = new System.IO.StreamReader(context.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }

        argsList = jsonSerializer.Deserialize<List<ArgsVals>>(jsonString);
        string resp = "";
        foreach (ArgsVals arg in argsList)
        {
            resp += arg.desid;
        }
        context.Response.Write("<text>"+resp+"</text>");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    public class ArgsVals
    {
        public string desid { get; set; }
        //public int vtype { get; set; }
    }
}

一切正常,直到控件离开context.Response.Write()语句。数据resp可以很好地获取数据。但问题是,Javascript显示此错误:JavaScript runtime error: Invalid character

我搜索了SO和其他网站。我也试过这个解决方案:Ajax request has invalid characters 但似乎没什么用。同样的错误仍然存​​在。

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试在响应中返回HTML / XML而不是JSON。

context.Response.Write("<text>"+resp+"</text>");

阅读JSON webpages,了解您要发回的邮件的结构。