ajax与json 获取数据并在前台使用简单实例

(编辑:jimmy 日期: 2024/10/1 浏览:2)

用ajax获取后台数据,返回json数据,怎么在前台使用呢?

后台


if (dataType == "SearchCustomer")
        {
          int ID;
          if (Int32.TryParse(CustomerID, out ID))
          {
            string s = GridComputer.GridCustomer.getCustomer(1, 1, ID);
            if (s == null)
            {
              context.Response.ContentType = "text/plain";
              context.Response.Write("[{\"name\":无用户,\"id\":\"0\",\"company\":\"无用户\"}]");
            }
            else { context.Response.Write(s); }
          }
 
        } 

前台


 $(document).ready(function () {
      $("#Button3").click(
    function (SucCallback) {
      $.ajax(
      {
        type: "get",
        url: 'GridDatas.ashx', //后台处理程序  
        dataType: 'json',   //接受数据格式  
        data: 'DataType=SearchCustomer&CustomerID=' + document.getElementById("Text3").value,     //要传递的数据  
        success:SucCallback,
        error: function () { alert("error"); }
      });
    })
    })

参考代码

grid.getCustomer(1,2,function (data) {
    var list = '<p>' + tree_GridInfo._name + '的用户有</p><br>';
    list += '<table id="customers"><tr><th>姓名</th><th>电话</th></tr> ';
    $.each(data, function (i, n) {
      list += '<tr onclick="showUser(' + 1 + ')"><td>';
      list += n.name + '</td>' + '<td>' + n.company;
      list += '</td></tr>';
    });
    $("#SearchResult").html(list)

看你的json数据是列表还是单个了,就一条就无需中括号了

context.Response.Write("{\"name\":无用户,\"id\":\"0\",\"company\":\"无用户\"}");

$(document).ready(function () {
      $("#Button3").click(
    function (SucCallback) {
      $.ajax(
      {
        type: "get",
        url: 'GridDatas.ashx', //后台处理程序  
        dataType: 'json',   //接受数据格式  
        data: 'DataType=SearchCustomer&CustomerID=' + document.getElementById("Text3").value,     //要传递的数据  
        function (dataJson) {
           alert(dataJson.Name);
           alert(dataJson.Id);
        },
        error: function () { alert("error"); }
      });
    })
    })

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

一句话新闻

一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?