无法获取jQuery的Ajax来解析JSON web服务的结果结果、Ajax、jQuery、web

2023-09-10 14:22:03 作者:把心熬成铁

我已经验证从我的C#的WebMethod JSON响应,所以我不相信这就是问题所在。

我试图解析使用简单的jQuery $阿贾克斯的结果,但由于某种原因,我不能得到的方法来正确地触发和分析的结果,还捎带似乎无法得到的功能来触发的结果。是他们对可以返回的JSON对象的大小的任何限制。

我也删除这code,从里面的Site.Master页面,因为它总是会刷新时,我打了简单的按钮。做标记与像按钮输入我从DOM抓住jQuery的元素都能正常工作?

 函数阿贾克斯(){
// VAR的myData = {QTYPE:产品名称,查询的Xbox};
VAR的myData = {请求:{QTYPE:产品名称,查询的Xbox}};
$阿贾克斯({
    键入:POST,
    网址:/webservice/WebService.asmx/updateProductsList
    数据:{InputData:$的toJSON(myData的)},
    的contentType:应用/ JSON的;字符集= UTF-8,
    数据类型:JSON,
    成功:函数(MSG){
        //无功味精= {__type:Testportal.outputData,ID:li1234,留言:这是工作,敏:101}
        警报(信息=+ msg.d.ProductName +,ID =+ msg.d.Brand);
    },
    错误:函数(RES,状态){
        如果(状态===错误){
            //的errorMessage可以是一个对象,具有3字符串属性:ExceptionType,消息和堆栈跟踪
            VAR的errorMessage = $ .parseJSON(res.responseText);
            警报(errorMessage.Message);
        }
    }
});
 

}

和页面:

 < ASP:按钮的ID =Button1的=服务器的OnClientClick =阿贾克斯();文本=按钮/>
 
web核心 11 jquery的ajax json数据 jackson转换工具 度娘搜索

而Serverside集团的WebMethod:

 公共类的WebService:System.Web.Services.WebService
{
    [WebMethod的]
    [ScriptMethod(UseHttpGet = TRUE,ResponseFormat = ResponseFormat.Json)
    公共OutputData updateProductsList(InputData要求)
    {
        OutputData结果=新OutputData();
        变种DB =新App_Data.eCostDataContext();
        变种Q =从C在db.eCosts
                选择C;

        如果(string.IsNullOrEmpty(request.qtype)及!&安培;!string.IsNullOrEmpty(request.query))
        {
            Q = q.Like(request.qtype,request.query);
        }

        // Q = q.Skip((页 -  1)* RP)。取(RP);
        result.products = q.ToList();

        sea​​rchObject搜索=新searchObject();

        的foreach(App_Data.eCost产品result.products)
        {
            / *创建新的项目清单* /
            信息搜索结果的元素=新的信息搜索结果()
            {
                ID = product.ProductID,
                元素= GetPropertyList(产品)
            };
            sea​​rch.items.Add(元素);
        }
        返回结果;

    }
 

和辅助类:

 公共类OutputData
{
    公共字符串ID {获得;组; }
    公开名单< App_Data.eCost>产品{获得;组; }

}
公共类InputData
{
    公共字符串QTYPE {获得;组; }
    公众查询字符串{获取;组; }
}
 

解决方案

你可能有一个问题是,你是不是从提交表单和执行一个完整的回发做任何prevent按钮/重载的同时你开始你的$。阿贾克斯()回调。

我会建议使用OnClientClick属性布线这件事悄悄地代替,像这样的:

  $(文件)。就绪(函数(){
  //可能需要使用$('<%= Button1.ClientID%>'),如果你的按钮
  //命名容器内,如母版页。
  $('#Button1的)。点击(函数(EVT){
    //这将停止的形式提交。
    。EVT preventDefault();

    $阿贾克斯({
      //你的$。阿贾克斯()code在这里。
    });
  });
});
 

我还与奥列格同意,你应该使用json2.js为您的JSON字符串化和解析。在新的浏览器,这将回落到这些方法,这是更快的浏览器的本地实现,使分析更安全。

更新:

要回答你的问题有关的数据,没有看起来不完全正确。

要最终发送到服务器这是什么(没有格式化):

  {请求:{GTYPE:产品名称,查询:的Xbox}}
 

要实现这个目标,你希望是这样的:

  VAR REQ = {要求:{QTYPE:产品名称,查询的Xbox}};

$阿贾克斯({
  数据:JSON.stringify(REQ),
  //剩余$。阿贾克斯()的参数
});
 

请注意,要求 QTYPE 查询必须在服务器端的结构,区分大小写的精度相匹配。

您也可以在定义请求对象(我preFER,身体力行,让事情变得清晰可读)更详细的:

  VAR REQ = {};

req.request = {};

req.request.qtype =产品名称;
req.request.query =的Xbox;
 

我已经写了一点关于这个在这里,如果你有兴趣:的http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

I have validated the JSON response from my C# Webmethod, so I don't believe that's the problem.

Am trying to parse the result using simple jQuery $.ajax, but for whatever reason I can't get the method to correctly fire and parse the result, also incidentally can't seem to get the function to fire the result. Are their any limits on the size of the JSON object that can be returned.

I also removed this code from inside a "Site.Master" page because it would always refresh when I hit the simple button. Do tags work correctly with jQuery elements like the button input I'm grabbing from the 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);
        }
    }
});

}

And the page:

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

And the 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;

    }

And helper classes:

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

解决方案

One problem you may be having is that you aren't doing anything to prevent the button from submitting the form and executing a full postback/reload at the same time you're starting your $.ajax() callback.

I'd suggest wiring this up unobtrusively instead of using the OnClientClick property, like this:

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

I also agree with Oleg that you should use json2.js for your JSON stringifying and parsing. In newer browsers, that will fall back to the browsers' native implementations of those methods, which is much faster and makes the parsing safer.

Update:

To answer your question about the data, no that doesn't look quite right.

What you want to ultimately send to the server is this (sans formatting):

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

To accomplish that, you want something like this:

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

$.ajax({
  data: JSON.stringify(req),
  // Remaining $.ajax() parameters
});

Keep in mind that request, qtype, and query must match your server-side structure with case-sensitive accuracy.

You can also be more verbose in defining the request object (which I prefer, personally, to keep things clear and readable):

var req = { };

req.request = { };

req.request.qtype = "ProductName";
req.request.query = "xbox";

I've written a bit more about this here, if you're interested: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/