簡體   English   中英

如何使用javascript從asp.net webservice中使用Json數據

[英]How to consume Json data from asp.net webservice with javascript

曾幾何時,有一個人在工作的項目。 該項目有一個母版頁和一個內容頁面。 內容頁面有一個下拉列表和兩個文本框。 但是,當這個人從下拉列表中選擇任何產品名稱時,有多好奇,它的totalQuantitypricePerItem值沒有出現在文本框中! 他試圖為這個項目編寫Web服務代碼和javascript代碼,但不幸的是,它並沒有按照他應該和將要做的那樣做。 因此,他正在請求你的幫助。

 public class QuantityAndPrice
{
    public string totalQuantity { get; set; }
    public string pricePerItem { get; set; }
}

網絡服務代碼

  public class QuantityAndPriceService : System.Web.Services.WebService
{

    [WebMethod]
    public void GetQuantityAndPrice(string productName)
    {
        QuantityAndPrice quantityAndpriceObject = new QuantityAndPrice();

        string connect_string = "datasource=localhost;port=3306;username=root;password=root;";
        MySqlConnection connection = new MySqlConnection(connect_string);
        string query = "select totalQuantity,pricePerItem from smart_shop.inventory where name='" + productName + "';";
        MySqlCommand  cmd = new MySqlCommand(query, connection);
        connection.Open();
        MySqlDataReader   reader = cmd.ExecuteReader();



        while (reader.Read())
        {
            quantityAndpriceObject.totalQuantity = reader.GetString("totalQuantity");
            quantityAndpriceObject.pricePerItem = reader.GetString("pricePerItem");
        }

        JavaScriptSerializer js = new JavaScriptSerializer(); 
       Context.Response.Write(js.Serialize(quantityAndpriceObject));


    }
}

JavaScript的

  <script type="text/javascript"> $(document).ready(function () { $('#productNameDDL').change(function () { var pName = $('#productNameDDL').val(); $.ajax({ url: 'QuantityAndPriceService.asmx/GetQuantityAndPrice', data: { productName: pName }, method: 'post', dataType: 'json', success: function (data) { $('#tbxAvailableQuantity').val(data.totalQuantity); $('#tbxPricePerItem').val(data.pricePerItem); }, error: function (err) { alert(err); } }); }); }); </script> 

這里是aspx代碼

<div class="panel-body">
                <div class="row">
                    <div class="col-md-6"> 
                         <h6>&nbsp;&nbsp;Available Qty</h6>
                         <asp:TextBox ID="tbxAvailableQuantity" CssClass="form-control" ReadOnly="true" runat="server"></asp:TextBox>
                    </div>

                    <div class="col-md-6">
                         <h6>&nbsp;&nbsp;Price/Item</h6>
                          <asp:TextBox ID="tbxPricePerItem" CssClass="form-control" ReadOnly="true" runat="server"></asp:TextBox>
                    </div>

                </div> 
                <div class="row">
                    <div class="col-lg-6">
                         <h6>&nbsp;&nbsp;Sales Qty</h6>
                         <asp:TextBox ID="tbxSalesQtuantity" CssClass="form-control" runat="server"></asp:TextBox>
                    </div>
                    <div class="col-lg-6">
                         <h6>&nbsp;&nbsp;Total Price</h6>
                         <asp:TextBox ID="tbxTotalPrice" CssClass="form-control" runat="server"></asp:TextBox>
                    </div>
                </div>                 

            </div>




  <asp:DropDownList ID="productNameDDL" CssClass="form-control" runat="server"></asp:DropDownList>
  1. Web服務類應該具有ScriptService屬性。
  2. Web服務方法應該有ScriptMethod屬性來指定ResponseFormat = ResponseFormat.Json
  3. 在java腳本中, contentType: "application/json; charset=utf-8"dataType: 'json'應該被指定。
  4. ajax調用成功部分的結果包含在d例如像data.d.totalQuantity
  5. ajax調用中的數據應該被字符串化,例如像這樣的data:JSON.stringify({ productName: pName })

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class QuantityAndPriceService : WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public QuantityAndPrice GetQuantityAndPrice(string productName)
    {
        QuantityAndPrice quantityAndpriceObject = new QuantityAndPrice
        {
            totalQuantity = "totalQuantityValue",
            pricePerItem = "pricePerItemValue"
        };
        return quantityAndpriceObject;
    }
}

$.ajax({
    url: 'QuantityAndPriceService.asmx/GetQuantityAndPrice',
    data: JSON.stringify({ productName: pName }),
    method: 'post',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
        $('#tbxAvailableQuantity').val(data.d.totalQuantity);
        $('#tbxPricePerItem').val(data.d.pricePerItem);
    },
    error: function (err) {
        alert(err.responseText);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM