asp.net jquery ajax json:交换数据的简单示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11269622/
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
asp.net jquery ajax json: Simple example of exchanging data
提问by Eric Schneider
(Question resolved with the help of the two reply posts--see below)
(问题在两个回复帖子的帮助下解决了——见下文)
I would appreciate help getting a simple example of exchanging data JSON data between a browser (using JavaScript/JQuery) and ASP.NET (using Visual Studio 2010).
我希望能得到一个在浏览器(使用 JavaScript/JQuery)和 ASP.NET(使用 Visual Studio 2010)之间交换数据 JSON 数据的简单示例。
When I click a button the following is executed:
当我单击一个按钮时,将执行以下操作:
<script type="text/javascript">
bClick = function () {
var myData = { "par": "smile" };
alert("hi "+myData.par);
$.ajax({
url: "ericHandler.ashx",
data: myData,
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("DIDit = " + data.eric); },
error: function (data, status, jqXHR) { alert("FAILED:" + status); }
});
}
</script>
In Visual Studio, I have the following code associated with an ashx file. When I run it and click the button, everything works as expected except I don't see myData passed to the C# code--I am looking at context.Request.QueryString in the debugger and it shows "{}".
在 Visual Studio 中,我有以下与 ashx 文件关联的代码。当我运行它并单击按钮时,一切都按预期工作,除了我没有看到 myData 传递给 C# 代码——我在调试器中查看 context.Request.QueryString 并显示“{}”。
I have seen examples using
我见过使用的例子
string stringParam = (string)Request.Form("stringParam");
but Visual Studio "Request" does not seem to be defined. All I want to do is see data move both ways, and I appear to be half way there. Any help would be appreciated.
但似乎没有定义 Visual Studio“请求”。我想要做的就是看到数据双向移动,而我似乎已经完成了一半。任何帮助,将不胜感激。
--C# code--
--C#代码--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CSASPNETSerializeJsonString
{
/// <summary>
/// Summary description for ericHandler
/// </summary>
public class ericHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string rq = context.Request.QueryString["par"];
context.Response.ContentType = "application/json";
context.Response.Write("{\"eric\":\"12345\"}");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
}
*RESOLVED First, if you want to send some form parameters from JavaScript to ASP.NET one should use the ajax call in the second post below and do NOT use stringify on the data. In other words, if don't specify the data being sent is json the lack of any specification defaults to 'application/x-www-form-urlencoded'). This will causes the object's fields to be appended in a "url" format (field=X&field2=Y&field3=Z..) and thus shows up in ASP.NET using Request.Form["field"].
* 已解决首先,如果您想将一些表单参数从 JavaScript 发送到 ASP.NET,则应使用下面第二篇文章中的 ajax 调用,并且不要对数据使用 stringify。换句话说,如果不指定要发送的数据是 json,则缺少任何规范默认为“application/x-www-form-urlencoded”)。这将导致对象的字段以“url”格式附加(field=X&field2=Y&field3=Z..),从而使用 Request.Form["field"] 在 ASP.NET 中显示。
Second, if you really do want to send JSON data, then specify this type is what is being sent (like I have done above) and use the InputStream on the receiving side. Further parsing of the received string is then required to get at the field values.
其次,如果你真的想发送 JSON 数据,那么指定这个类型是什么正在发送(就像我上面所做的那样)并在接收端使用 InputStream 。然后需要进一步解析接收到的字符串以获得字段值。
In my example, I am sending back JSON data having "manually" encoded it into a string. I believe there is a JSON serialization routine so that C# objects can be sent over.
在我的示例中,我发送回“手动”将其编码为字符串的 JSON 数据。我相信有一个 JSON 序列化例程,以便可以发送 C# 对象。
回答by DaveB
Other resource suggest removing the contentType: 'application/json; charset=utf-8',
from the AJAX call:
其他资源建议contentType: 'application/json; charset=utf-8',
从 AJAX 调用中删除:
$.ajax({
url: "ericHandler.ashx",
data: myData,
dataType: 'json',
type: 'POST',
success: function (data) { alert("DIDit = " + data.eric); },
error: function (data, status, jqXHR) { alert("FAILED:" + status); }
});
Read the values on the server side:
读取服务器端的值:
string myPar = context.Request.Form["par"];
You can also try:
你也可以试试:
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
which was mentioned here: https://stackoverflow.com/a/8714375/139917
回答by Hanlet Esca?o
I got this working right away. This is its most basic form:
我马上就开始工作了。这是它最基本的形式:
HTML:
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'Handler.ashx',
type: 'POST',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error");
}
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
Code Behind:
背后的代码:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}