【问题标题】:How to consume Json data from asp.net webservice with javascript如何使用 javascript 使用来自 asp.net webservice 的 Json 数据
【发布时间】:2017-03-26 13:40:31
【问题描述】:

从前,有一个人正在从事一个项目。这个项目有一个母版页和一个内容页。内容页面有一个下拉列表和两个文本框。然而,当这个人从下拉列表中选择任何产品名称时,多么奇怪的是,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>

【问题讨论】:

  • data.d 包含 asp.net web 表单中的所有对象

标签: javascript c# asp.net json web-services


【解决方案1】:
  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);
    }
});

【讨论】:

  • 我不明白我缺少什么仍然无法正常工作,但用于检查运行 QuantityAndPriceService.asmx 何时返回预期值但未出现在文本框中
  • 有一个人正在努力解决的问题。然而,当这个人提交他的答案时,多么好奇,它仍然不起作用。也许这个人会问,到底是什么不工作?
  • 我在我的项目中使用了这段代码,但没有工作......我很抱歉......它出现了 json 数据,但没有显示在文本框中
  • 我不能说为什么这不起作用,但here on my dropbox 你可以找到一个完整的示例解决方案,我已经测试过这个问题。对我来说,它就是这样工作的。 HTH
猜你喜欢
  • 1970-01-01
  • 2018-06-24
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 2021-06-08
  • 2013-03-15
  • 1970-01-01
相关资源
最近更新 更多