【问题标题】:Format data (client-side) for (server-side)为(服务器端)格式化数据(客户端)
【发布时间】:2011-07-13 15:05:35
【问题描述】:

使用以下脚本:

$("#some_button").click(function() {

    var changed = [];

    $( 'input[id$="_0"]' ).each(function() {

        var new_id = this.id.replace( '_0', '_1' );

        if ( $(this).val() !== $( 'input#' + new_id ).val() ) {

            changed.push(new_id);
            // send back id, new value from _0, and old value from _1

        }

    });

    console.log(changed);

});

我需要将id、来自_1 的旧值和来自_0 的新值发回服务器。格式化此数据的最佳方法是什么,以便我可以轻松地从服务器端提取数据,以便我可以轻松地向某人发送电子邮件,例如让他们知道哪些文本框已更改,旧值是什么以及新值是什么

在服务器端,我使用的是 .NET-3.5 (VB)。

我知道如何将数据发送回。以及如何通过电子邮件发送数据,我只是想知道如何在发送回数据之前最好地在客户端格式化数据。


我最多可以发回 50 组 id、旧值和新值。很抱歉之前没有说清楚。


示例:

如何修改上面的脚本来生成这个?

[
    {
        "id": "name_0",
        "new": "text",
        "old": "text"
    },
    {
        "id": "age_0",
        "new": "text",
        "old": "text"
    },
    {
        "id": "dept_0",
        "new": "text",
        "old": "text"
    }
]

【问题讨论】:

  • 请看上面的例子。我可以使用 jquery.serialize / jquery.serializeArray 来实现吗?

标签: javascript jquery .net asp.net vb.net


【解决方案1】:

在客户端:

changed.push(new_id)

改为

changed.push({id:new_id, new_val:$(new_id).val(), old_val:$(this).val()});

稍后:

$.post(TARGET_URL, changed);

在服务器端:

using System.Web.Script.Serialization;
// ...
public class Change {
    public string id {get; set; }
    public string new_val {get; set; }
    public string old_val {get; set; }
}
List<Change> changes = new JavaScriptSerializer().Deserialize(data_string);

旧答案,由于运输的物品很多,已过时。

如果您的数据足够短,只需在 url 中编码即可。

var url = TARGET_URL + "?old_id="+escape(old_id)+"&new_id="+escape(new_id);

【讨论】:

  • 我最多可以发回 50 组 id、旧值和新值。很抱歉之前没有说清楚。
  • 请看上面有问题的新例子。
  • 答案现在可以与您的示例一起使用,并将创建所需的格式。 (虽然你看不到。)我读到,你使用的是 VB,但我认为它很容易翻译。
【解决方案2】:
var data = '{"0":[{"old_id":" + $(this).val() + '"},{"old_id":"' + new_id + '"}]}';

通过 ajax POST 发送,并使用 DataContractJsonSerializerFlexJson 进行解析

结果将如下所示:

{
    "0": [
        {
            "old_id": "foo"
        },
        {
            "old_id": "bar"
        }
    ],
    "1": [
        {
            "old_id": "foo2"
        },
        {
            "old_id": "bar2"
        }
    ],
    "2": [
        {
            "old_id": "foo3"
        },
        {
            "old_id": "bar3"
        }
    ]
}

【讨论】:

  • 我最多可以发回 50 组 id、旧值和新值。很抱歉之前没有说清楚。
  • 请看上面有问题的新例子。
  • 已更新 - 只需使用 JSON 数组 :)
【解决方案3】:

JSON 是一种非常好的、精简的数据交换格式。

这样的东西,可能会起作用:

var changed = [];

$( 'input[id$="_0"]' ).each(function() {
    var thisItemChanges = { id: this.id, newid = this.id.replace('_0', '_1') };
    changed.push(thisItemChanges);
});

$.post('UrlToPostTo', changed,  function(serverResponse) { // do something with return from server });

另请参阅jQuery.post,了解有关使用 javascript 向服务器发送数据的更多信息。

【讨论】:

  • 我最多可以发回 50 组 id、旧值和新值。很抱歉之前没有说清楚。
  • 请看上面有问题的新例子。
猜你喜欢
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多