ajax and json get data and use simple examples in the foreground

  • 2021-07-12 05:13:47
  • OfStack

Use ajax to obtain background data and return json data. How to use it in the foreground?

Backstage



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\": No user ,\"id\":\"0\",\"company\":\" No user \"}]");
            }
            else { context.Response.Write(s); }
          }
 
        } 

Front desk



 $(document).ready(function () {
      $("#Button3").click(
    function (SucCallback) {
      $.ajax(
      {
        type: "get",
        url: 'GridDatas.ashx', // Background handler   
        dataType: 'json',   // Accept data format   
        data: 'DataType=SearchCustomer&CustomerID=' + document.getElementById("Text3").value,     // Data to pass   
        success:SucCallback,
        error: function () { alert("error"); }
      });
    })
    })

Reference code


grid.getCustomer(1,2,function (data) {
    var list = '<p>' + tree_GridInfo._name + ' Users of are </p><br>';
    list += '<table id="customers"><tr><th> Name </th><th> Telephone </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)

See if your json data is a list or a single one, so there is no need for brackets


context.Response.Write("{\"name\": No user ,\"id\":\"0\",\"company\":\" No user \"}");

$(document).ready(function () {
      $("#Button3").click(
    function (SucCallback) {
      $.ajax(
      {
        type: "get",
        url: 'GridDatas.ashx', // Background handler   
        dataType: 'json',   // Accept data format   
        data: 'DataType=SearchCustomer&CustomerID=' + document.getElementById("Text3").value,     // Data to pass   
        function (dataJson) {
           alert(dataJson.Name);
           alert(dataJson.Id);
        },
        error: function () { alert("error"); }
      });
    })
    })

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: