简体   繁体   中英

How do i get data from different tables using JQuery

I have 2 tables eg

public class Block
  {
public int ID{ set; get; }
public string Name{ set; get; }
public string Price { set; get; }
}

public class Room
{
public int ID{ set; get; }
public string Name{ set; get; }
public string Price { set; get; }
}

From these tables how would i select price from different table? Eg When a user selects a Name (from Block class) and Name (from Room class). Each Name has its own Price, IF a user selects BlockA that has a price of $22 (from Block class) and SeatingRoom that has a price of $25(from Room class) Javascript should add them and display the addition in different web-page: This DEMO outlines what i need but instead having values in drop down menu how do I retrieve it from the database, so that onClick Search button it will display the calculation. This is my Ajax method that gets the place name and populates into a dropdown menu.

        function Method() {
        ajReq = $.ajax({
            type: "POST",
            url: "Services/",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var opts = '';
                $.each(data.d, function (i) {
                    opts += '<li>' + '<a class="">' + this.Name+ '</a>' + '</li>';

                });
                $('.Dropdown').html(opts);
            }
        });
    }

This is my onclick button:

        $(document).on("click", "#buttonClick", function () {
  });

My webmethod for Ajax:

        [WebMethod]
    public IEnumerable<Room> Method()
    {
        List<Room> r= data.getRoom();
        return r;
    }
data is my class name and getRoom is a method
    public List<ToBooking> getRoom()
    {
        List<Room> t= new List<Room>();
        SqlConnection myConnection = new etc..);
        SqlCommand myCommand = new SqlCommand("SELECT * FROM TableName", myConnection);

        myConnection.Open();
        SqlDataReader reader = myCommand.ExecuteReader();
        while (reader.Read())
        {
                            b.Name= reader["Name"].ToString();
        }

    }


         <div class="btn-group">
            <button type="button" id="blockss" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                <span id="headingFrom">From:</span><span class="caret"></span>
            </button>
            <ul class="dropdown-menu Dropdown">
                <li><a class=""></a></li>
            </ul>
        </div>

You seem to be using Java as the server-side language, but you've including nothing about how the back end actually works. The simplest answer is that you need to follow this pattern:

  1. Write a REST function in Java to handle a particular type of AJAX call like a database lookup.
  2. Call that REST function with jQuery providing the right parameters.
  3. Have the jQuery callback insert the data correctly into the DOM however you want.

If I were implementing this, I'd use Apache CXF for the REST. CXF is generally the easiest thing I've seen for beginners to write a clean service layer in Java these days for something like this.

Here is a sample webmethod:

[System.Web.Services.WebService(Namespace = "http://tempuri.org/")]
[System.Web.Services.WebServiceBinding(ConformsTo = System.Web.Services.WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Demo : System.Web.Services.WebService
{
    public class Block
    {
        public int ID { set; get; }
        public string Name { set; get; }
        public string Price { set; get; }
    }
    [System.Web.Services.WebMethod]
    public List<Block> GetBlockList()
    {
        List<Block> result = new List<Block>();
        using (DataTable dt = new DataTable())
        {
            using (SqlConnection conn = new SqlConnection("Sql Connection String Here"))
            {
                string sql = "SELECT id, name, price FROM tableName WHERE block = @block";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    try
                    {
                        conn.Open();
                    }
                    catch (Exception e)
                    {
                        string ex = e.ToString(); // Do something with the error
                    }
                    dt.Load(cmd.ExecuteReader());
                }
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                result.Add(new Block(){
                    ID = int.Parse(dt.Rows[i].ItemArray.GetValue(0).ToString()),
                    Name = dt.Rows[i].ItemArray.GetValue(1).ToString(),
                    Price = dt.Rows[i].ItemArray.GetValue(2).ToString()
                });
            }
        }
        return result;
    }
}

And now the AJAX to generate a dropdown list along with the event handler for the dropdown to display the price when the selection changes:

$(document).ready(function (){
    $.ajax({
        type: "POST",
        url: "/Services/GetBlockList",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        failure: function () { alert("failure"); },
        error: function () { alert("error"); },
        success: function (response) {
            var row = response.d;
            var html = "<select id=\"BlockList\">";
            html += "<option value=\"0\">Select</option>";
            $.each(row, function (index, item) {
                html += "<option value=\"" + item.Price + "\">";
                html += item.Name;
                html += "</option>";
            });
            html += "</select>";
            $("#htmlBody").append(html);
        }
    });
    $("#BlockList").change(function () {
        alert("Price: " + $(this).val());
    });
});

This is the basics of it. You can, of course, do a lot more with AJAX than just generating a dropdown, but this should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM