首页 > 代码库 > 一个AJAX的请求。讲诉Json的使用示例

一个AJAX的请求。讲诉Json的使用示例

mvc使用JsonResult返回Json数据 


<控制器>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using JSON.Models;

namespace JSON.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取年龄
        /// </summary>
        /// <param name="username"></param>
        /// <returns>返回一个字符串</returns>
        public ActionResult GetAge(string username)
        {
            var age = "";
            if (!string.IsNullOrWhiteSpace(username))
            {
                string sql = "select Age from t_user where UserName=@username";
                age = (SqlHelper.ExecuteScalar(sql, new SqlParameter("username", username))).ToString();
            }
            return Content(age); 

        }
        /// <summary>
        /// 获取姓名
        /// </summary>
        /// <param name="id"></param>
        /// <returns>方法放回一个Table表的Json对象</returns>
        public ActionResult GetName(int id)
        {
            string sql = "select * from t_user where id=@id";
            DataTable dt=SqlHelper.ExecuteDataTable(sql,new SqlParameter("id",id));
            var data = http://www.mamicode.com/DataTableToJson.ToJson(dt); //调用DataTableToJson类的ToJson方法,将dt这边表转换成Json格式>

<视图>

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
</head>
<body>
    <div id="div1" style="color: Red">
    </div>
    <div id="div2" style="color: Blue">
    </div>
    <input type="button" value="获取姓名" id="btnClick" />
</body>
<script type="text/javascript">
    $.ajax({
        url: "/Home/GetAge",
        type: "get",
        //async: true,
        dataType: "json",
        data: { username: "周晶" },
        success: function (ajaxData) {
            $("#div1").text(ajaxData);
        }
    });


</script>
<script type="text/javascript">
    $(function () {
        $("#btnClick").click(function () {
            $.ajax({
                url: "/Home/GetName",
                dataType: "json",
                type: "get",
                data: { id: "1" },
                success: function (Dbdata) {
                    //debugger; 如果你要调试的话,就在这里写上debugger执行的时候就会跳到这里来了。然后按F10往下执行

                    //console.log('Dbdata', Dbdata); //在浏览器控制台输出日志

                    var str = Dbdata.MyData; //获取key为MyData的这个Json字符串

                    //console.log('str', str);

                    var obj = eval('(' + str + ')'); //将str这个Json格式的字符串转换成对象

                    //console.log('obj', obj);

                    //alert('username: ' + obj.UserName);
                    $("#div2").text(obj.UserName); 

                }
            })      
        })

    })
    
</script>
</html>

SQLHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Reflection;

namespace JSON.Controllers
{
    public class SqlHelper
    {
        /// <summary>
        /// 获取连接数据库字符串
        /// </summary>
        private static string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

        /// <summary>
        /// 执行查询,并将查询的结果以DataTable的形式返回
        /// </summary>
        /// <param name="sql">要执行的sql语句</param>
        /// <param name="parameters">sql语句的参数</param>
        /// <returns>返回值是一个DataTable</returns>
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                //换一种写法,与上面的几种写法稍稍有点不同
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(parameters);
                    DataTable dt = new DataTable();
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                        return dt;
                    }

                }
            }
        }

}


一个AJAX的请求。讲诉Json的使用示例