【问题标题】:Can't get jQuery Ajax to parse JSON webservice result无法让 jQuery Ajax 解析 JSON Web 服务结果
【发布时间】:2010-07-06 19:48:42
【问题描述】:

我已经验证了我的 C# Web 方法的 JSON 响应,所以我认为这不是问题所在。

我正在尝试使用简单的 jQuery $.ajax 解析结果,但无论出于何种原因,我都无法获得正确触发和解析结果的方法,顺便说一句,似乎也无法获得触发结果的函数。他们对可以返回的 JSON 对象的大小是否有任何限制。

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

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" /> 

以及服务器端 Web 方法:

 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; }
}

【问题讨论】:

  • 请注意:尝试用单引号包裹 qtype 和查询。即 "{'qtype': '" + qtype + "', 'query': '" + query + "'}";
  • 谢谢!这样做了,但没有新结果——还更新了 $.ajax 方法。
  • 对 JSON 的单引号使用不正确(请参阅 json.org 或在 jsonlint.com 中验证您的 JSON 数据)

标签: ajax json jquery


【解决方案1】:

您可能遇到的一个问题是,在您启动 $.ajax() 回调的同时,您没有做任何事情来阻止按钮提交表单并执行完整的回发/重新加载。

我建议不显眼地把它连接起来,而不是使用 OnClientClick 属性,像这样:

$(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
});

请记住,requestqtypequery 必须与您的服务器端结构匹配且区分大小写。

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

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/

【讨论】:

  • 谢谢!我也刚刚替换了 JS,因为注意到了一些错别字。我的数据看起来是否为网络方法正确格式化!是的,我想知道那个完整的帖子。
  • thansk Dave- 我真的是 Javascript 新手,之前没有用它来做任何像消化 WS 一样高效的事情,所以这很有趣但也有点乏味!非常感谢您抽出宝贵的时间
  • 感谢 Dave,我实际上有 Firebug,并且因为没有获得太多新信息而放弃使用它,但我确实使用了监视和断点。实际上,我最初的想法是从您的网站上留下我的 UpdatePanel:encosia.com 现在似乎可以工作了,我只需要解析 JSON 响应并将其放在 HTML 中,所以我仍在阅读。
  • 在 Firebug 中,您将能够在控制台选项卡中看到 $.ajax() 请求。单击加号图标以展开该打开,您将能够看到请求中发送的内容以及返回的内容。如果响应是 JSON,它也会很好地为您解析出来。这是 Firebug 中最能帮助您的部分。
【解决方案2】:

您的服务器端代码方法是什么样的?设置断点。是不是被击中了?

它应该看起来像:

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

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

【讨论】:

  • 谢谢,我刚刚将方法添加到帖子中。此外,在执行 jS 参数时。我已经成功使用这种格式在输入框中来回传递了一个简单的字符串,所以我决定不改变有效的方法! (至少为此)。我会尝试这种新格式。
【解决方案3】:

在我看来,您的问题是您尝试使用手动 JSON 序列化。还有更直接的方法。您应该只声​​明 [ScriptMethod (ResponseFormat = ResponseFormat.Json)][ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 并直接返回一个对象而不是来自 web 方法的字符串。在客户端(在 JavaScript 中)我强烈建议您使用 JSON.stringify(来自 json2.js,可以从 http://www.json.org/js.html 下载)来构造 jQuery.ajaxdata 参数。

看看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 你有兴趣进行更多实验。

【讨论】:

  • 谢谢奥列格,我要添加“ScriptMethod”(我以前有这个,但由于我也使用手动序列化而未能正确设置它),我喜欢这些帖子您告诉我将服务转换为“WFC Restful”服务是个好主意。如果运气好的话,我会用我的结果来回答这个问题。
  • 欢迎您!我想听听我的其他答案对您也有帮助。谢谢。也祝你好运,在软件开发方面取得巨大成功!
  • 谢谢,我根据我的阅读做了一些更改,但还无法正确格式化我的对象以发送到服务 - 我还在玩它,我知道我需要在我的 JSON 字符串中为 web 服务提供输入类型以供输入 - 但我不断收到:错误:对象不支持此属性或方法
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多