基本简单的 Asp.net + jQuery + JSON 示例

发布于 2024-11-02 21:17:06 字数 511 浏览 1 评论 0原文

我正在尝试学习如何从 Javascript/jQuery 对服务器进行简单的调用。我一直在努力学习,但找不到包含这些简单步骤的教程。

我想用两个参数(一个日期时间和一个字符串)向服务器发送一条消息并返回一个日期时间。我想通过 JSON 来做到这一点。

  • 服务器中的代码是什么样的(仅结构)?
  • 我应该在服务器端做一些特别的事情吗?安全性怎么样?
  • 我如何在 jQuery 中实现调用?
  • 我将如何处理结果?

我对代码结构最感兴趣。

更新

我发现下面的答案非常适合我开始。然而,我最近偶然发现了完整的 ASP. NET、LINQ、jQuery、JSON、Ajax 教程。这是一个非常棒且非常有指导意义的步骤,我想与将来遇到这个问题的其他人分享。

I'm trying to learn how to make a simple call to the server from Javascript/jQuery. I've been trying to learn and could not find a tutorial with those simple steps.

I want to send a message to the server with two parameters (a DateTime and a String) and get back a DateTime. I want to do that via JSON.

  • How would the code in the server look like (structure only)?
  • Is there something special I should do on the server side? And how about security?
  • How would I implement the call in jQuery?
  • And how would I handle the result?

I'm most interested on code structure.

Update

I found the answer below great to get me started. However, I recently stumbled upon Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial. It's just a fantastic and very didactic step-by-step that I want to share with anyone else who comes across this question in the future.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一杆小烟枪 2024-11-09 21:17:06

有多种方法可以做到这一点;这将作为一个例子。

您可以为 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

接下来,您需要在 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);    
    }

看看这是如何工作的。它会帮助你开始!

更新:我在 CodeReview StackExchange 上发布了此代码:https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example

There are several ways that you can do this; this will serve as a single example.

You could write something like this for your jQuery code:

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

Next, you need to create a "generic handler" in your ASP.net project. In your generic handler, use Request.Form to read the values passed in as json. The code for your generic handler could look something like this:

[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);    
    }

See how this work out. It will get you started!

Update: I posted this code at the CodeReview StackExchange: https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example

半衾梦 2024-11-09 21:17:06

如果您使用 jQuery,则可以使用 GET 或 POST 来完成。

$.get ('<url to the service>',
       { dateParam: date, stringParam: 'teststring' },
       function(data) {
          // your JSON is in data
       }
);

$.post ('<url to the service>',
       { dateParam: date, stringParam: 'teststring' },
       function(data) {
          // your JSON is in data
       }
);

请注意,(例如 dateParam、stringParam)中的参数名称需要与您的服务方法所需的参数名称相同。此外,您的服务需要将结果格式化为 JSON,回调中的数据参数将包含您的服务发回的任何内容(例如文本、xml、json 等)。

请参阅 $.ajax、$.get、$.post 的 jQuery 文档: http://api.jquery .com/jQuery.ajax/http://api.jquery.com/jQuery。获取/http://api.jquery.com/jQuery.post/

If you are using jQuery you could do it with a GET or POST.

$.get ('<url to the service>',
       { dateParam: date, stringParam: 'teststring' },
       function(data) {
          // your JSON is in data
       }
);

$.post ('<url to the service>',
       { dateParam: date, stringParam: 'teststring' },
       function(data) {
          // your JSON is in data
       }
);

Note that the name of the parameters in (e.g. dateParam, stringParam) need to be the same as the name of the parameters your service method is expecting. Also that your service will need to format the result as JSON, the data parameter in the call back will contain anything your service sends back (e.g. text, xml, json, etc).

See the jQuery documentation for $.ajax, $.get, $.post: http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.get/, http://api.jquery.com/jQuery.post/

策马西风 2024-11-09 21:17:06

这里的示例代码使用 jquery ajax 调用并在服务器端 webmethod 返回 jSon 格式数据。
Jquery :

$(‘#myButton’).on(‘click’,function(){
    var aData= [];
     aData[0] = “2010”; 
     aData[0]=””    
     var jsonData = JSON.stringify({ aData:aData});
       $.ajax({
                type: "POST",
                url: "Ajax_function/myfunction.asmx/getListOfCars",  //getListOfCars is my webmethod 
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json", // dataType is json format
                success: OnSuccess,
                error: OnErrorCall
            });
   
function OnSuccess(response.d)) {
console.log(response.d)
}
function OnErrorCall(response)) { console.log(error); }
});

代码隐藏 : 这是一个返回 json 格式数据的 webmethod,即汽车列表

[webmethod]
public List<Cars> getListOfCars(list<string> aData) 
{
    SqlDataReader dr;
    List<Cars> carList = new List<Cars>();
         
         using (SqlConnection con = new SqlConnection(cn.ConnectionString))
         {
            using (SqlCommand cmd = new SqlCommand())
            {
               cmd.CommandText = "spGetCars";
               cmd.CommandType = CommandType.StoredProcedure;
               cmd.Connection = con;
               cmd.Parameters.AddWithValue("@makeYear", aData[0]);
               con.Open();
               dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
               if (dr.HasRows)
               {
                  while (dr.Read())
                   {    
                       string carname=dr[“carName”].toString();
           string carrating=dr[“carRating”].toString();
            string makingyear=dr[“carYear”].toString();
           carList .Add(new Cars{carName=carname,carRating=carrating,carYear=makingyear}); 
        }
                }
            }
          }
        return carList 
        }

//创建了一个类

Public class Cars {
public string carName;
public string carRating;
public string carYear;
}

Here sample code using jquery ajax call and on serverside webmethod returns jSon format data.
Jquery :

$(‘#myButton’).on(‘click’,function(){
    var aData= [];
     aData[0] = “2010”; 
     aData[0]=””    
     var jsonData = JSON.stringify({ aData:aData});
       $.ajax({
                type: "POST",
                url: "Ajax_function/myfunction.asmx/getListOfCars",  //getListOfCars is my webmethod 
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json", // dataType is json format
                success: OnSuccess,
                error: OnErrorCall
            });
   
function OnSuccess(response.d)) {
console.log(response.d)
}
function OnErrorCall(response)) { console.log(error); }
});

Codebehind : Here a webmethod which is returning json format data i.e list of cars

[webmethod]
public List<Cars> getListOfCars(list<string> aData) 
{
    SqlDataReader dr;
    List<Cars> carList = new List<Cars>();
         
         using (SqlConnection con = new SqlConnection(cn.ConnectionString))
         {
            using (SqlCommand cmd = new SqlCommand())
            {
               cmd.CommandText = "spGetCars";
               cmd.CommandType = CommandType.StoredProcedure;
               cmd.Connection = con;
               cmd.Parameters.AddWithValue("@makeYear", aData[0]);
               con.Open();
               dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
               if (dr.HasRows)
               {
                  while (dr.Read())
                   {    
                       string carname=dr[“carName”].toString();
           string carrating=dr[“carRating”].toString();
            string makingyear=dr[“carYear”].toString();
           carList .Add(new Cars{carName=carname,carRating=carrating,carYear=makingyear}); 
        }
                }
            }
          }
        return carList 
        }

//Created a class

Public class Cars {
public string carName;
public string carRating;
public string carYear;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文