代码之家  ›  专栏  ›  技术社区  ›  jordan.baucke

无法让jQuery Ajax解析JSON webservice结果

  •  3
  • jordan.baucke  · 技术社区  · 16 年前

    我尝试使用simple jQuery$.ajax解析结果,但是不管出于什么原因,我都无法获得正确激发和解析结果的方法,而且似乎也无法获得激发结果的函数。它们对可以返回的JSON对象的大小没有任何限制。

    我还从“Site.Master”页面中删除了这段代码,因为当我点击简单的按钮时,它总是会刷新。标记与jQuery元素(如我从DOM中获取的按钮输入)是否正常工作?

    function ajax() {
    //var myData = { qtype: "ProductName", query: "xbox" };
    var myData = { "request": { qtype: "ProductName", query: "xbox"} };
    $.ajax({
        type: "POST",
        url: "/webservice/WebService.asmx/updateProductsList",
        data: {InputData:$.toJSON(myData)},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // var msg = {__type: "Testportal.outputData", id: "li1234", message: "it's work!", myInt:101}
            alert("message=" + msg.d.ProductName + ", id=" + msg.d.Brand);
        },
        error: function (res, status) {
            if (status === "error") {
                // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
                var errorMessage = $.parseJSON(res.responseText);
                alert(errorMessage.Message);
            }
        }
    });
    

     <asp:Button ID="Button1" runat="server" OnClientClick="ajax();"  Text="Button" /> 
    

    以及服务器端Webmethod:

     public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public OutputData updateProductsList(InputData request)
        {
            OutputData result = new OutputData();
            var db = new App_Data.eCostDataContext();
            var q = from c in db.eCosts
                    select c;
    
            if (!string.IsNullOrEmpty(request.qtype) && !string.IsNullOrEmpty(request.query))
            {
                q = q.Like(request.qtype, request.query);
            }
    
            //q = q.Skip((page - 1) * rp).Take(rp);
            result.products = q.ToList();
    
            searchObject search = new searchObject();
    
            foreach (App_Data.eCost product in result.products)
            {
                /* create new item list */
                searchResult elements = new searchResult()
                {
                    id = product.ProductID,
                    elements = GetPropertyList(product)
                };
                search.items.Add(elements);
            }
            return result;
    
        }
    

    和助手类:

        public class OutputData
    {
        public string id { get; set; }
        public List<App_Data.eCost> products { get; set; }
    
    }
    public class InputData
    {
        public string qtype { get; set; }
        public string query { get; set; }
    }
    
    3 回复  |  直到 15 年前
        1
  •  1
  •   Dave Ward    16 年前

    $(document).ready(function() {
      // May need to use $('<%= Button1.ClientID %>') if your Button is 
      //  inside a naming container, such as a master page.
      $('#Button1').click(function(evt) {
        // This stops the form submission.
        evt.preventDefault();
    
        $.ajax({
          // Your $.ajax() code here.
        });
      });
    });
    

    我也同意Oleg的观点,您应该使用json2.js进行JSON字符串化和解析。在较新的浏览器中,这将回到浏览器对这些方法的本地实现,这将大大加快解析速度并使解析更加安全。

    更新:

    回答你关于数据的问题,不,那看起来不太对。

    {"request":{"gtype":"ProductName","query":"xbox"}}
    

    要做到这一点,你需要这样的东西:

    var req = { request : { qtype: "ProductName", query: "xbox" }};
    
    $.ajax({
      data: JSON.stringify(req),
      // Remaining $.ajax() parameters
    });
    

    request , qtype ,和 query

    您还可以更详细地定义请求对象(我个人更喜欢这样做,以保持清晰易读):

    var req = { };
    
    req.request = { };
    
    req.request.qtype = "ProductName";
    req.request.query = "xbox";
    

    如果你感兴趣的话,我在这里写了更多的内容: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

        2
  •  1
  •   Kris Krause    16 年前

    它应该看起来像:

    [WebMethod, ScriptMethod]
    public string updateProductsList(string qtype, string query)
    { // stuff
    }
    

    另外,javascript数据参数的格式看起来也不正确。

        3
  •  1
  •   Community Mohan Dere    9 年前

    在我看来,您的问题是您试图使用手动JSON序列化。有更直接的方法。你应该申报一下 [ScriptMethod (ResponseFormat = ResponseFormat.Json)] [ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 并直接返回一个对象,而不是web方法中的字符串。在客户端(在JavaScript中),我严格建议您使用 JSON.stringify (来自json2.js,点击 http://www.json.org/js.html )为了建造 data 的参数 jQuery.ajax .

    看看 Can I return JSON from an .asmx Web Service if the ContentType is not JSON? How do I build a JSON object to send to an AJAX WebService? 可能也在 JQuery ajax call to httpget webmethod (c#) not working