【问题标题】:How to get return value of WebMethod from JQuery如何从 JQuery 中获取 WebMethod 的返回值
【发布时间】:2016-03-30 06:56:05
【问题描述】:

我正在尝试从 JQuery 调用中获取 WebMethod 的返回值,但我收到“未定义”消息。下面是我的代码

$.ajax({
        type: "POST",
        url: "Receipt/BarcodeEntered",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function (msg) {
                    alert(msg.d); // This displays "Undefined"
                    alert(msg);   // This displays the whole html
                 }
});

WebMethod 在下面

[WebMethod]
public static string BarcodeEntered() 
{
    return "test_string";
}

如何从 WebMethod 获取值并将其显示在客户端?

【问题讨论】:

    标签: c# jquery asp.net webforms


    【解决方案1】:

    WebMethod 官方只能返回 XML 或 JSON。 默认是 json,所以无论你返回什么都会被转换成 json

    JQuery 的变化 dataType: "json",

    $.ajax({
            type: "POST",
            url: "Receipt/BarcodeEntered",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                        alert(msg);
                     }
    });
    

    你应该返回类而不是单个字符串。因为字符串不能转换为有效的json对象。

    public class SampleClass{
        public string Message {set; get;}
    }
    
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public SampleClass BarcodeEntered()
    {
    
            return new SampleClass(){
            Message  = "Sample message"
        };
    
    }
    

    【讨论】:

      【解决方案2】:

      你需要返回JSON,我写一个例子。

      public JsonResult DoStuff()
      {
          string text = "text";
      
          return Json(text, JsonRequestBehavior.AllowGet);
      }
      

      【讨论】:

        【解决方案3】:

        这是我在我的 asp.net 页面中使用的工作演示。数据将在 d 属性中。

        JQuery 代码。

            $.ajax({
            type: "POST",
            url: "/Subfolder/MyPageName.aspx/myWebMethodName",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
              if (msg.d == "OK") {
               alert("OK")
              } else {
                 alert(msg.d);
              }
            }
           });
        

        C#代码

        [WebMethod]
        public static string myWebMethodName()
        { 
           return "OK";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-07
          • 1970-01-01
          • 1970-01-01
          • 2011-11-05
          • 1970-01-01
          • 2013-12-17
          相关资源
          最近更新 更多