在 ASHX AJAX C# 中获取 JSON

5
在Home.aspx页面中有一个脚本:
<script type="text/javascript">
  function probarAjax() {

    var Publicaciones = {
      "Categoria": "Noticia"
    }

    $.ajax({
      type: "POST",
      url: "Controlador.ashx?accion=enviar",
      data: JSON.stringify(Publicaciones),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data) {
        console.log(data);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
      }

    });
  }
</script>

在 Controlador.ashx 内部:

public void ProcessRequest(HttpContext context) {
  context.Response.ContentType = "text/json";

  var categoria = string.Empty;
  JavaScriptSerializer javaSerialize = new JavaScriptSerializer();
  categoria = context.Request["Categoria"];

  var capaSeguridad = new { d = categoria };

  context.Response.Write(javaSerialize.Serialize(capaSeguridad));
}

结果如下:

Object {d: null} 

为什么会出现这个结果?如果我在数据中发送一个参数,该参数的变量名为Publicaciones,其值为"Noticia"

解决方案是这个。 - Vesper
3个回答

0

添加

context.Response.ContentType = "application/json";

到你的ASHX方法。


0

解决方案是这样的

   <script type="text/javascript">
    function probarAjax() {

        var Publicaciones = {
               "Categoria" : "Noticia"                  
        }

        $.ajax({
            type: "POST",
            url: "Controlador.ashx?accion=enviar",
            data: JSON.stringify(Publicaciones),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log(data.d);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }


        });
    }    

</script>

ashx 文件内部

   public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/json";

        System.IO.Stream body = context.Request.InputStream;
        System.Text.Encoding encoding = context.Request.ContentEncoding;
        System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);

        string s = reader.ReadToEnd();
        Noticia publicacion = JsonConvert.DeserializeObject<Noticia>(s);
        var capaSeguridad = new { d = publicacion.Categoria };

        context.Response.Write(JsonConvert.SerializeObject(capaSeguridad));
    }

使用类

public class Noticia
    {
        public string Categoria { get; set; }
    }

谢谢帮我


当我使用JsonConvert.DeserializeObject进行反序列化时,会出现异常,提示“无法将当前的JSON数组(例如[1,2,3])反序列化为类型'SurplusApp.items',因为该类型需要一个JSON对象。” - Coded Container
如果对象包含Publicaciones数组,那么它会是什么样子? - Coded Container

0

更改为:data: Publicaciones

原代码为:data: JSON.stringify(Publicaciones)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接