c# - 在 ASHX AJAX C# 中获取 JSON

标签 c# ajax json ashx

在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"

最佳答案

解决方案是这样的

   <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));
    }

与类(class)

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

谢谢你帮助我

关于c# - 在 ASHX AJAX C# 中获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22374316/

相关文章:

c# - 为什么我超出了内存限制? C#

ruby-on-rails - 如何缓存渲染:json

ajax - 有没有支持 AJAX 的优秀拖放 Web 应用程序 IDE?

ajax - CakePHP 使用 ajax 加载模态内容

c++ - 在 C++ 中使用 JSON 序列化 OpenCv Mat

php - 将 json 对象检索到 xCode 中始终带有 nil 值

c# - 字典大小显式初始化: pros and cons

c# - 在特定屏幕上启动进程

c# - 在页面之间传递多个变量并使用它们

javascript - 如何通过 HTTP POST 将 Blob 发送到不同的域?