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

问题描述:

我在学习如何从Javascript/jQuery做一个简单的调用服务器。我一直在努力学习,无法通过这些简单的步骤找到教程。基本简单Asp.net + jQuery + JSON示例

我想用两个参数(一个DateTime和一个字符串)发送消息到服务器并获取一个DateTime。我想通过JSON来做到这一点。

  • 服务器中的代码如何看起来像(只有结构)?
  • 有什么特别的我应该在服务器端做?那安全怎么样?
  • 我将如何在jQuery中实现调用?
  • 我将如何处理结果?

我对代码结构最感兴趣。

更新

我发现下面伟大的答案,让我开始。不过,我最近偶然发现了Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial。这只是一个非常神奇而且非常教导性的步骤,我想与未来遇到这个问题的其他人分享。

+0

你会碰巧拥有你提到的文章的源代码吗?我非常感兴趣,但我不清楚要使用哪些文件。更具体地说,我应该创建一个ASP.NET网站吗?或者用C#编写的类应该包含在Web服务中?我只是不确定在哪些文件类型中组织一些代码。 – Darren 2012-07-06 01:47:02

+0

这里是一步一步的文章http://codepedia.info/2015/02/jquery-ajax-json-example-asp-net-sql-database/关于如何在asp.net中做一个简单的jquery ajax调用 – 2015-09-01 11:14:39

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

你可以写这样的事情对你的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);  
    } 

看看如何解决这个问题。它会让你开始!

更新:我发布这个代码在代码审查StackExchange:使用jQuery Ajax调用服务器端上的WebMethod返回JSON格式的数据https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example

+0

注意:如果您在使用json时遇到问题,请务必向Google提供一个良好的json验证程序。 – 2011-04-22 14:47:00

+0

另请注意:文字'jQuery in Action'有很好的jQuery方面的例子。 – 2011-04-22 14:58:53

+0

我在做实验,会让你知道! – 2011-04-22 15:16:43

如果你使用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,回调中的数据参数将包含您的服务返回的任何内容(例如,text,xml,json等)。

见jQuery的文档$阿贾克斯,和$ .get,$。员额:http://api.jquery.com/jQuery.ajax/http://api.jquery.com/jQuery.get/http://api.jquery.com/jQuery.post/

+0

请请注意,'get'和'post'的默认内容类型是'application/x-www-form-urlencoded;字符集= UTF-8'。所以这不会通过Json发送数据到服务器。被接受的答案在哪里。 – Liam 2014-03-25 14:21:00

下面的示例代码。 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格式数据I A的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; 
} 

博客文章:

+0

警告此代码有很多错误,虽然它确实指向了正确的方向。 – 2016-12-07 00:21:29