javascript 如何从 Aspx 页面发送 Json 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11613194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send Json Data from Aspx page
提问by Pratik
I tried to use TokenInput Jquery for multiple value autocomplete where it requires the JSON response as input data
我尝试使用 TokenInput Jquery 进行多值自动完成,它需要 JSON 响应作为输入数据
http://loopj.com/jquery-tokeninput/
http://loopj.com/jquery-tokeninput/
I am using ASPX page as source
我使用 ASPX 页面作为源
<script type="text/javascript" >
$(document).ready(function() {
$("#txtTest").tokenInput("Complete.aspx", {
theme: "facebook"
});
});
</script>
Edited From HereQuestion: How to provide the JSON data from a aspx page in the desired format as i have datatable with values according to Querystring from Complete.aspx
从这里编辑问题:如何从 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();
}
}
Any help will be appreciated.
任何帮助将不胜感激。
采纳答案by adatapost
Alternative to the WCF
, you can create WebMethod
in .aspx.
替代WCF
,您可以WebMethod
在 .aspx 中创建。
[WebMethod]
public static string Info()
{
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(new string[] { "one", "two", "three" });
return result;
}
and request this WebMethod via Ajax call.
并通过 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>
EDIT:
编辑:
Code-behind - Page_Load handler (JsonPage.aspx)
代码隐藏 - Page_Load 处理程序 (JsonPage.aspx)
string json = "[{\"name\":\"Pratik\"},{\"name\": \"Parth\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
and request the JsonPage.aspx
via TokenInputjQuery
. (Sample.aspx & JsonPage.aspx are in same folder)
并请求JsonPage.aspx
via TokenInputjQuery
。(Sample.aspx 和 JsonPage.aspx 在同一个文件夹中)
<script type="text/javascript">
$(function () {
$("#txt1").tokenInput("JsonPage.aspx");
});
</script>
<body>
<input type="text" id="txt1"/>
</body>
回答by Chris Snyder
You should take a look at WCF. WCF has native support for returning JSONand you don't have to worry about string concatenation or HTTP content types.
你应该看看WCF。 WCF 对返回 JSON 具有本机支持,您不必担心字符串连接或 HTTP 内容类型。