从ASMX返回JSON,用正确方式处理它在Javascript它在、正确、方式、ASMX

2023-09-11 00:33:55 作者:拿稳的你心

我知道有吨的类似的问题已经在这里,但我不明白这一个。

I realize there are tonnes of similar questions already up here but I cannot figure this one out.

我有一个Web服务(C#,.NET 3.5)。你需要知道的基本code是如下:

I have a Web Service (C#, .net 3.5). The essential Code you need to know of is as follows:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WSMember : System.Web.Services.WebService {

    public WSMember () {   
    }


    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string GetMember(string IdMember)
    {
        //Ignore the parameter for now... I will be looking up a database with it... 
        //For now just return a minimal object:
        Member m = new Member();
        m.Surname = "Smith";
        m.FirstName = "John";
        return new JavaScriptSerializer().Serialize(m);
    }

此外,在web.config中,我做了如下补充(我只是看到了一些其他的职位...这是正常的/安全吗?)

Also, in web.config, I made the following addition (which I just saw on some other post... is this normal/safe?)

  <webServices>
      <protocols>
        <add name="HttpGet" />
        <add name="HttpPost" />
      </protocols>
    </webServices>

然后Default.aspx中,我的两个重要参考...

Then in Default.aspx, I the two key references...

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript" src="jquery.json-2.2.min.js"  ></script>

jquery.json-2.2.min.js从谷歌code下载

jquery.json-2.2.min.js was downloaded from google code

这里是JavaScript:

And Here is the Javascript:

<script type="text/javascript">
         $(document).ready(function() {
             $("#button1").click(function(event) {
                 var myData = { IdMember: "2" };
                 var encoded = $.toJSON(myData);

                 alert(encoded);

                 $.ajax({
                     type: "POST",
                     url: "WSMember.asmx/GetMember",
                     data: encoded,
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function(msg) {
                         alert("worked" + msg.d);
                         //$("#sidebar").append(msg);
                     },
                     error: function(msg) {
                         alert(msg.d);
                         //$("#sidebar").append(msg);
                     }
                 });
             });
         });

    </script>

当我执行它时,EN codeD JSON作为预期会出现在消息框中...即用双引号:

When I execute it, the encoded json appears in the message box as expected... i.e. with double quotes:

{IdMember:2}

{ "IdMember":"2" }

然而,它总是失败。即使是最基本的Hello World与正在传递中没有数据,它失败。我不断收到未定义的消息数据。

However, it always fails. Even for the most basic Hello World with no data being passed in, it fails. I keep getting "undefined" for the message data.

如果我只是用警报(味精),显示[对象XMLHtt prequest]

If I just use alert(msg), it displays [object XMLHttpRequest]

有谁知道我的数据迷路?

Does anyone know where my data is getting lost??

和另外一个问题...有什么根本性错误我在做什么?

And another question... is there anything fundamentally wrong with what I'm doing?

多谢了。

编辑:

感谢您的答复家伙。我曾尝试以下这样...

thanks for the reply guys. I have tried the following so...

UseHttpGet =真现更改为false。 (再次 - 我看到了它的地方,所以我尝试过......但我知道这不可能是正确的: - /)

UseHttpGet = true is now changed to false. (Again - I saw it somewhere so I tried it... but I knew it couldn't be right :-/ )

比方说,Web服务现在返回一个字符串。我建立了串如下(好像有点疯狂......其序列做了同样的事情...)

Let's say the web service now returns a string. I build the string as follows (seems a bit crazy... serializing it did the exact same thing... )

    StringBuilder sb = new StringBuilder();
    sb.Append("{");
    sb.Append("\"Surname\":");
    sb.Append("\"");
    sb.Append(m.Surname);
    sb.Append("\"");

    sb.Append(",\"FirstName\":");
    sb.Append("\"");
    sb.Append(m.FirstName);
    sb.Append("\"");

    sb.Append("}");

    return sb.ToString();

这code返回是这样的:

This code returns something like:

{"Surname":"Smith","FirstName":"John"}

我仍然会得到完全相同的错误...

I still get the exact same error...

我也试着像返回对象会员,因此code就变成了:

I have also tried something like returning the object "Member",so the code becomes:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Member GetMember(string IdMember)
{
    Member m = new Member();
    m.Surname = "Smith";
    m.FirstName = "John";

    return m;
}

这也引发了同样的错误。

This too throws the same error.

对不起,是一个痛苦......我读过这两个环节,和其他人。只是不明白为什么这有什么不同。

Sorry to be a pain... I've read both of those links, and others. Just can't see why this any different.

有没有我需要知道的可能是任何额外的配置设置??

Is there any extra config setting I need to be aware of possibly??

非常感谢你的答复。

更新: 问题是固定的。在上述code关键的错误是:

UPDATE: Problem is fixed. The key mistakes in the above code are:

[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

此外,在窗体上,用一个按钮来调用JavaScript的时候,我被错误地设置输入型...

Also, on the form, when using a button to call the javascript, I was incorrectly setting the input type...

<input id="button1" type="submit" value="Just a test" />

在它的应该说:

<input id="button1" type="button" value="Just a test" />

感谢所有谁帮助。

Many thanks to all who helped.

推荐答案

在我看来,这一尝试手动使用 JavaScriptSerializer()。序列化,而不是你的主要问题的返回的对象。从Web服务的响应将是双JSON EN codeD。

It seems to me that your main problem that you try to manually use JavaScriptSerializer().Serialize instead of returning an object. The response from the web service will be double JSON encoded.

您是对的!有很多的亲密问题。看看这里http://stackoverflow.com/questions/2670147/can-i-return-json-from-an-asmx-web-service-if-the-contenttype-is-not-json/2671583#2671583和http://stackoverflow.com/questions/3189653/cant-get-jquery-ajax-to-parse-json-webservice-result/3190823#3190823你会(我希望)找到了答案。

You are right! There are a lot of a close questions. Look at here http://stackoverflow.com/questions/2670147/can-i-return-json-from-an-asmx-web-service-if-the-contenttype-is-not-json/2671583#2671583 and http://stackoverflow.com/questions/3189653/cant-get-jquery-ajax-to-parse-json-webservice-result/3190823#3190823 and you will (I hope) find the answer.

更新时间::很抱歉,但你有一个小错误,你没有张贴什么地方。要关闭的问题,我创建了一个旧版本的Visual Studio(VS2008)的一个小项目,实际上具有完全的code,哪些工作。我把它放在 http://www.ok-soft-gmbh.com/jQuery /WSMember.zip 。您可以下载,编译并验证它的工作原理。然后,你可以用我的比较你的code,并找到自己的错误。

UPDATED: Sorry, but you have a small error somewhere what you didn't posted. To close the problem I created a small project with an old version of Visual Studio (VS2008) which has practically exactly your code and which work. I placed it on http://www.ok-soft-gmbh.com/jQuery/WSMember.zip. You can download it, compile and verify that it works. Then you can compare your code with my and find your error.

最好的问候