0

サーバー側関数を呼び出して、json 形式の文字列を返し、javascript と ajax を使用してクライアント側で解析しています。javascript で解析エラーが発生しました。JavaScriptSerializer がオブジェクトをシリアライズするために追加するバックスラッシュだと思います。これがfirebugからの応答です: {"d":"{\"Item\":\"Testing\"}"} 、バックスラッシュが二重引用符をエスケープすることであることは理解していますが、jsonでこれを修正するにはどうすればよいですか問題??私は 3 日間かけて、Google ですべての検索を行います。私も他の人と同じようにやっているようです。手伝ってくれてありがとう。

サーバー側コード:

[System.Web.Services.WebMethod]
public static string testmethod(string serial)
{ 
    ItemList itemlist = new ItemList();
    itemlist.Item = "Testing";     
    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(itemlist);
}

[System.Runtime.Serialization.DataContract]
public class ItemList
{
    [System.Runtime.Serialization.DataMember]
    public string Item { get; set; }
}

ajax を使用したクライアント側 Javascript:

function PassParemeterToAspxUsingJquery(serial)
{               
    var sn = "test";//serial;
    $.ajax({
    type: "POST",
    url: "test.aspx/testmethod",
    contentType: "application/json; charset=utf-8",
    data: "{serial:'" + sn+"'}" ,
    dataType: "json",
    success: function(msg) {           
       alert(msg.d);             
    },
    error: function(jqXHR, textStatus, errorThrown){
       alert("The following error occured: "+ textStatus, errorThrown);
       alert(jqXHR.responseText);
    }
    });
}
4

1 に答える 1

1

JSON テキストの一部として値を埋め込みませWebMethodん。JSON 文字列ではなく JSON オブジェクトとしてシリアル化する場合は、ではなくを返す必要があります。ObjectString

[System.Web.Services.WebMethod]
public static object testmethod(string serial)
{
    ItemList itemlist = new ItemList();
    itemlist.Item = "Testing";
    return itemList;
}

ただし、これには .NET 3.5 と以下が必要になる場合がありますScriptMethodAttribute

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static object testmethod(string serial)
{ ... }

それからちょうど:

success: function(msg) {
   alert(msg.d.Item);
}

または、解析することでそのまま使用できるはずですmsg.d

success: function(msg) {
    var data = $.parseJSON(msg.d);

    alert(data.Item);
}
于 2012-05-23T18:46:31.263 に答える