C# 如何从JQuery中获取WebMethod的返回值
我试图从JQuery调用中获取WebMethod的返回值,但是我得到了“undefined”消息。下面是我的代码C# 如何从JQuery中获取WebMethod的返回值,c#,jquery,asp.net,webforms,C#,Jquery,Asp.net,Webforms,我试图从JQuery调用中获取WebMethod的返回值,但是我得到了“undefined”消息。下面是我的代码 $.ajax({ type: "POST", url: "Receipt/BarcodeEntered", data: "{}", contentType: "application/json; charset=utf-8", dataType: "text", success: func
$.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官方只能返回XML或JSON。 默认值为json,因此返回的任何内容都将转换为json JQuery中的更改
数据类型:“json”,
您应该返回类而不是单个字符串。因为字符串不能转换为有效的json对象
public class SampleClass{
public string Message {set; get;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public SampleClass BarcodeEntered()
{
return new SampleClass(){
Message = "Sample message"
};
}
WebMethod官方只能返回XML或JSON。 默认值为json,因此返回的任何内容都将转换为json JQuery中的更改
数据类型:“json”,
您应该返回类而不是单个字符串。因为字符串不能转换为有效的json对象
public class SampleClass{
public string Message {set; get;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public SampleClass BarcodeEntered()
{
return new SampleClass(){
Message = "Sample message"
};
}
您需要返回JSON,让我写下一个示例
public JsonResult DoStuff()
{
string text = "text";
return Json(text, JsonRequestBehavior.AllowGet);
}
您需要返回JSON,让我写下一个示例
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#代码
这是我在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#代码