加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在ASHX AJAX C#中获取JSON

发布时间:2020-12-16 02:55:45 所属栏目:百科 来源:网络整理
导读:在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: "ap
在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}

为什么会这样?如果我使用值为“Noticia”的变量Publicaciones在数据中发送参数.

解决方法

解决方案就是这样

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

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

        $.ajax({
            type: "POST",success: function (data) {
                console.log(data.d);
            },error: function (XMLHttpRequest,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; }
    }

谢谢你的帮助

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读