我尝试了一个简单的网络服务(只是测试该值是否会在 JavaScript 代码上生成)。我尝试了一个非常简单的代码片段,但随后返回“未定义”。请指教。我尝试了一些解决方案,但没有成功。
这里是asmx文件的简单代码
[WebMethod]
public string HelloWorld(string param1, string param2)
{
return "Hello World" + param1 + ":" + param2;
}
这是我的 javascript 上的代码。
$.ajax({
url: "SimpleService.asmx/HelloWorld",
type: "POST",
data: {
'param1': 'value1',
'param2': 'value2'
},
success: function(response) {
alert(response.d);
}
});
我尝试使用 response.text 和 response.value 获取结果,但我仍然得到一个未定义的值。
success: function(response) {
alert(response.text);
alert(response.value);
}
在我的 asmx 文件中, 我也尝试将 [WebMethod] 替换为。
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(string param1, string param2)
{
return "Hello World" + param1 + ":" + param2;
}
请告知从我的网络服务获取结果的正确格式是什么。
谢谢
最佳答案
你应该把 [ScriptService]
属性放到你的服务类中,如下所示
[ScriptService]
public class SimpleService : System.Web.Services.WebService
之后,更改您的 ajax 调用。将 contentType 和更改数据如下:
$.ajax({
url: "SimpleService.asmx/HelloWorld",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ param1: 'value1', param2: 'value2' }",
success: function (response) {
alert(response.d);
}
});
关于javascript - Web 服务 C# 返回未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969702/