Asp.net WebMethod-返回字符串[]并使用JavaScript进行解析

Asp.net WebMethod - return string[] and parse it using JavaScript

本文关键字:JavaScript WebMethod- net 返回 字符串 Asp      更新时间:2023-09-26

我需要在codeehind从MyMethod返回一个字符串数组。但我是否使用javascript在aspx页面上解析它?

[WebMethod]
public static string[] MyMethod(){
   return new[] {"fdsf", "gfdgdfgf"};
}
..........
function myFunction() {
            $.ajax({ ......
                    success: function (msg) {
                                //how do I parse msg?
                                }
            });
        };

首先,确保您已经用[ScriptService]标记了类,以允许通过AJAX调用它。类似于:

[ScriptService] //<-- Important
public class WebService : System.Web.Services.WebService
{
   [ScriptMethod] //<-- WebMethod is fine here too
   public string[] MyMethod()
   {
      return new[] {"fdsf", "gfdgdfgf"};
   }
}

然后,您可以直接使用jQuery读取结果,因为不需要解析任何内容:

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "WebService.asmx/MyMethod",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      // msg.d will be your array with 2 strings
    }
  });
});

另一种方法是只引用:

<script src="WebService.asmx/js" type="text/javascript"></script>

这将生成代理类,允许您直接调用web方法。例如:

WebService.MyMethod(onComplete, onError);

onComplete函数将接收一个包含web服务调用结果的参数,在您的情况下是一个包含2个字符串的Javascript数组。在我看来,这是一个比使用jQuery和担心URL和HTTP负载更容易的解决方案。

使用jQuery迭代器像这样迭代msg结果中的字符串。

function myFunction() {
    $.ajax({ ......
        success: function (msg) {
            $.each(msg, function(index, value) {
                alert(value);
            });
        }
    });
};

响应object将包含一个名为d的对象,该对象封装从WebMethod返回的值。访问方式如下:

function myFunction() {
    $.ajax({ ......
        success: function (msg) {
            //how do I parse msg?
            alert(msg.d); //alerts "fdsf", "gfdgdfgf"
        }
    });
};

有关解释,请参阅此问题。