【问题标题】:handle an arrray posted with $.ajax (jquery) to a webservice处理使用 $.ajax (jquery) 发布到 Web 服务的数组
【发布时间】:2010-04-22 14:35:39
【问题描述】:

我正在尝试将数据发布到 web 服务 (asp.net 3.5),如下所示(两个变体,一个已评论):

var array = [3, 2, 5, 1, 7];
var jsonString = JSON.stringify(array);
//var jsonString = '{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }'

$.ajax({
    type: "POST",
    url: "WebService2.asmx/AddRoute",
    data: jsonString,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    processData: "false",
    error: function(msg) {
        alert('error' + msg.toString);
    }
});

所以我需要一个匹配的网络方法来接收它。像这样的:

[WebMethod]
public string AddRoute(/* xxx */)
{
    //handle data
}

谁能详细说明我如何获取数据,我在哪里输入了“xxx”? 我原以为“int []数组”可以解决问题,但它不起作用。 任何帮助将不胜感激:)

【问题讨论】:

  • 你可以作弊,将其声明为object,用调试器中断该方法,看看它实际上是什么类型。
  • 另外,基于 JavaScript 的注释掉位,这可能有用encosia.com/2009/04/07/…

标签: c# jquery ajax web-services


【解决方案1】:

我不熟悉 ASP.NET,但应该有一些方法可以让您获取使用 jQuery.ajax() 传递的请求参数。

$.ajax({
    type: "POST",
    url: "WebService2.asmx/AddRoute",
    **data: {'some_data': jsonString},**
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    processData: "false",
    error: function(msg) {
        alert('error' + msg.toString);
    }
});

请求参数是 some_data。从您的控制器中,您可以检索请求参数,而无需将其作为参数传递给您的函数。

由于我来自 Python/Pylons 背景,我很抱歉它含糊不清。

【讨论】:

    【解决方案2】:

    您应该只公开一个 asp.net mvc 操作方法,而不是 .asmx Web 服务。 Phil Haack 的这篇文章展示了接受强类型 json 数据(包括数组)是多么容易:
    http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

    【讨论】:

    • R0MANARMY 和 Joel,非常感谢您的回复!我通过网络服务让它按照“encosia”中描述的方式工作。所以我现在坚持这一点。但是,我稍后也会研究 mvc。并不是说我打算接收任何错误 :D 但如果我这样做了,它们显然会更容易使用 mvc 处理。再次感谢您抽出时间。我真的很感激!
    【解决方案3】:

    试试下面的代码:
    您也可以使用 int[] 而不是 string[]


    [WebInvoke(UriTemplate = "ServiceName", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
    public string ServiceName(string[] ids)

    【讨论】:

      【解决方案4】:

      这样声明你的服务类

      [ServiceContract(Namespace = "")]
      [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
      [System.Web.Script.Services.ScriptService]
      public class WFSrvc
      {
          // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
          // To create an operation that returns XML,
          //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
          //     and include the following line in the operation body:
          //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
          [OperationContract]
          public void DoWork()
          {
              // Add your operation implementation here
              return;
          }
      
          [OperationContract]
          [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
          [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
          public string HelloWorld()
          {
              return "Hello World";
      
          }
      

      }

      你可以使用自己的函数来代替 helloworld

      【讨论】:

        【解决方案5】:

        你的 ajax 帖子需要是这样的

        $.ajax({
            type: 'POST',
            url: 'WebService2.asmx/AddRoute',
            data: '{arr:'+ JSON.stringify(array)+'}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (msg) {
                 console.log(msg.d);
                 }
        });
        

        和你的网络方法

        [WebMethod]
        public string AddRoute(int[] arr) //parameter name and the name in data:{} should be same
        {
            //handle data
        }
        

        【讨论】:

          猜你喜欢
          • 2011-03-07
          • 2011-10-30
          • 2011-09-13
          • 1970-01-01
          • 1970-01-01
          • 2012-10-04
          • 2012-05-05
          相关资源
          最近更新 更多