如何从 JQuery 获取 WebMethod 的 return 值

How to get return value of WebMethod from JQuery

我正在尝试从 JQuery 调用中获取 WebMethod 的 return 值,但我收到 "undefined" 消息。下面是我的代码

$.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 获取值并将其显示在客户端?

WebMethod 官方只能 return XML 或 JSON。 默认是 json,所以无论你 return 被转换成 json

JQuery的变化dataType: "json",

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

你应该 return class 而不是单个字符串。因为字符串无法转换成有效的json对象。

public class SampleClass{
    public string Message {set; get;}
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public SampleClass BarcodeEntered()
{

        return new SampleClass(){
        Message  = "Sample message"
    };

}

你需要returnJSON,我写个例子吧

public JsonResult DoStuff()
{
    string text = "text";

    return Json(text, JsonRequestBehavior.AllowGet);
}

这是我在 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";
}