Adr*_*iro 29 c# asp.net ajax jquery json
我正在尝试学习如何从Javascript/jQuery对服务器进行简单的调用.我一直在努力学习,无法通过这些简单的步骤找到教程.
我想用两个参数(DateTime和String)向服务器发送消息并返回DateTime.我想通过JSON做到这一点.
我对代码结构最感兴趣.
更新
我发现下面的答案很棒,让我开始.但是,我最近偶然发现了完整的ASP.NET,LINQ,jQuery,JSON,Ajax教程.这是一个非常棒的,非常有说服力的一步一步,我想与将来遇到这个问题的其他人分享.
Dan*_*don 25
有几种方法可以做到这一点; 这将作为一个例子.
你可以为你的jQuery代码写这样的东西:
urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function(data) {
setAutocompleteData(data.responseDateTime);
},
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
Run Code Online (Sandbox Code Playgroud)
接下来,您需要在ASP.net项目中创建"通用处理程序".在通用处理程序中,用于Request.Form
读取作为json传入的值.通用处理程序的代码可能如下所示:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
string stringParam = (string)Request.Form["stringParam"];
// Your logic here
string json = "{ \"responseDateTime\": \"hello hello there!\" }";
context.Response.Write(json);
}
Run Code Online (Sandbox Code Playgroud)
看看这是如何工作的.它会让你开始!
更新:我在CodeReview StackExchange上发布了此代码:https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example
归档时间: |
|
查看次数: |
96467 次 |
最近记录: |