如何从Aspx页面发送Json数据

How to send Json Data from Aspx page

本文关键字:Json 数据 Aspx      更新时间:2024-01-21

我尝试使用TokenInput Jquery进行多值自动完成,它需要JSON响应作为输入数据

http://loopj.com/jquery-tokeninput/

我正在使用ASPX页面作为源

<script type="text/javascript" >
    $(document).ready(function() {
    $("#txtTest").tokenInput("Complete.aspx", {
        theme: "facebook"
    });
    });

</script>

从此处编辑问题:如何以所需格式提供aspx页面中的JSON数据,因为我有根据Complete.aspx 中Querystring的值的数据表

 protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["q"]))
    {
        string json = "[{'"Id'":'"1'",'"name'": '"Test 1'"},{'"Id'":'"2'",'"name'": '"Test 2'"}]";
        Response.Clear(); 
        Response.ContentType = "application/json; charset=utf-8"; 
        Response.Write(json); 
        Response.End();              
    }
}  

任何帮助都将不胜感激。

除了WCF,您还可以在.aspx.中创建WebMethod

   [WebMethod]
    public static string Info()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string result = js.Serialize(new string[] { "one", "two", "three" });
        return result;
    }

并通过Ajax调用请求此WebMethod。

<script type="text/javascript">
        $(function () {
            $("#button1").click(function () {
                $.ajax({
                    url: "Default.aspx/Info",
                    data: "{}",
                    contentType: "application/json",
                    success: function (data) {
                        alert(data.d);
                    },
                    type: "post",
                    dataType : "json"
                });
            });
        });
</script>

编辑:

代码隐藏-Page_Load处理程序(JsonPage.aspx)

  string json = "[{'"name'":'"Pratik'"},{'"name'": '"Parth'"}]";
  Response.Clear();
  Response.ContentType = "application/json; charset=utf-8";
  Response.Write(json);
  Response.End();

并通过TokenInputCCD_ 4请求CCD_。(Sample.aspx和JsonPage.aspx在同一文件夹中)

<script type="text/javascript">
        $(function () {
            $("#txt1").tokenInput("JsonPage.aspx");
        });
</script>
<body>
 <input type="text" id="txt1"/>
</body>

您应该了解WCF。WCF本机支持返回JSON,您不必担心字符串串联或HTTP内容类型。