2010-07-06 118 views
3

我已验证来自C#Webmethod的JSON响应,所以我不认为这是问题所在。无法获取jQuery Ajax来解析JSON webservice结果

我试图解析结果使用简单的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" /> 

而且Serverside集团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; } 
} 
+0

只是一个注意:尝试包装qtype和查询单引号。即“{'qtype':'”+ qtype +“','query':'”+ query +“'}”; – Marko 2010-07-06 19:52:54

+0

谢谢!这是否,没有新的结果 - 也更新了$ .ajax方法。 – 2010-07-06 20:34:50

+0

单引号的使用对于JSON不正确(请参阅http://www.json.org/或在http://www.jsonlint.com/上验证您的JSON数据) – Oleg 2010-07-06 23:01:58

回答

1

的一个问题是,你没有做任何事情来阻止提交表单,并在同一时间执行完全回发/重装你开始你的$。阿贾克斯()回调的按钮。

我建议布线这件事悄悄地而不是使用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. 
    }); 
    }); 
}); 

我也奥列格同意,你应该使用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/

+0

谢谢!我也只是将JS取代为注意到的一些错别字。 我的数据看起来像是格式正确的Web方法!是的,我想知道这个完整的帖子。 – 2010-07-07 22:13:23

+0

thansk Dave-我真的很少使用Javascript,并没有用它来做任何事情,就像以前一样消化WS,所以这很有趣,但也有点乏味!我真的很感谢你花时间 – 2010-07-08 01:08:26

+0

谢谢戴夫,我其实有Firebug,因为我没有得到太多新信息而放弃使用它,但我确实使用了手表和断点。 我实际上有最初的想法让我的UpdatePanels落后于你的网站:http://encosia.com 它似乎现在工作,我只需要解析JSON响应并将其放置在HTML中,所以我仍在阅读。 – 2010-07-08 01:38:24

1

你的服务器端代码方法是什么样的?设置一个中断点。它被击中了吗?

它应该是这个样子:

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

而且,你的JavaScript数据PARAMS看起来不正确格式化。

+0

谢谢,我只是将该方法添加到帖子中。另外,当做jS params。我已经成功地使用这种格式从输入框来回传递一个简单的字符串,所以我决定不改变什么工作! (至少为此)。我试试这个新格式。 – 2010-07-06 20:28:20

1

在我看来,你的问题是你尝试使用手动JSON序列化。有更直接的方法。您应该声明[ScriptMethod (ResponseFormat = ResponseFormat.Json)][ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)],并直接返回对象而不是web方法中的字符串。在客户端(在JavaScript)我严格推荐您使用JSON.stringify(从中可以从http://www.json.org/js.html下载json2.js)为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你有更多的实验兴趣。你可能有

+0

感谢Oleg,我将添加“ScriptMethod”(以前我曾经这样做过,但是由于我使用的是手动序列化,所以无法正确设置),我喜欢你给我提供的关于转换服务的文章到“WFC Restful”服务是个不错的主意。如果我有好运气,我会用我的结果回答这个问题。 – 2010-07-07 15:11:26

+0

欢迎您!我想听听我的其他答案对你也有帮助。谢谢。祝你好运,并在软件开发方面取得很大成功! – Oleg 2010-07-07 15:25:45

+0

谢谢,我根据自己的阅读做了一些更改,但尚未能够正确格式化对象以发送到服务 - 我仍在玩它,我看到我需要给出输入类型webservice在我的JSON字符串输入 - 但我不断收到:错误:对象不支持此属性或方法 – 2010-07-07 21:30:47