简体   繁体   English

JavaScript-从使用Json.Net创建的JSON对象提取数据

[英]JavaScript - extracting data from a JSON object created with Json.Net

I have a server-side method used to return the data to the user. 我有一个服务器端方法,用于将数据返回给用户。 The data is stored in a SQL Server database and is mapped using EF 6. Once extracted from the database using an id value, the object is subsequently serialized using the Json.NET framework. 数据存储在SQL Server数据库中,并使用EF 6进行映射。使用ID值从数据库中提取数据后,随后将使用Json.NET框架对对象进行序列化。 The object is used "as is", without filtering out the references to other tables. 该对象按原样使用,而不过滤掉对其他表的引用。 Because of that, I've had to use the "PreserveReferencesHandling" option. 因此,我不得不使用“ PreserveReferencesHandling”选项。 On the client-side, AJAX is used to call the method. 在客户端,使用AJAX调用该方法。 I'm having trouble extracting the data from the object (client-side) which does get serialized and is delivered to the browser as expected. 我在从对象(客户端)提取数据时遇到麻烦,该对象确实已序列化并按预期传递给浏览器。

Server-side method: 服务器端方法:

[WebMethod]
public static string ContactData(long id)
{
    IService<Contact> contactService = new ContactService();
    Contact contactEdit = contactService.GetById(id);

    string str = JsonConvert.SerializeObject(contactEdit, new JsonSerializerSettings
    {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
    });

    return str;
}

Client-side function (the important part): 客户端功能(重要部分):

$.ajax({
    type: "POST",
    url: "Contacts.aspx/ContactData",
    data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (contact) {
        $("#tbFirstName").val(contact.d[0].Contact.first_name); // I've tried various combinations to no avail
                },
});

This is how the JSON object (testing purposes data) looks like in Visual Studio's JSON Visualizer: 这是JSON对象(测试目的数据)在Visual Studio的JSON Visualizer中的样子:

JSON可视化工具

And this is what the browser (FF 32, it that matters) receives: 这就是浏览器(重要的是FF 32)接收到的内容:

Firebug 萤火虫

I will post more info if needed. 如果需要,我将发布更多信息。

First parse the json before you process it. 首先解析json,然后再处理它。 and loop through it using jquery each function. 并使用jquery每个函数遍历它。

    $.ajax({
        type: "POST",
        url: "Contacts.aspx/ContactData",
        data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (contact)
                {
                    var contact=jQuery.parseJSON(contact);
                    $.each(contact, function(i, item) {
                        alert(i + " ==> "+  item.first_name);
                    });

                 }

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM