我想通过单击按钮从我的 Html-Jquery 调用此 GetData 方法
$.ajax({
type: "GET",
url: "http://localhost:49313/WebForm.aspx/GetData/",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response);
}
});
但是我收到如下错误。请让我知道我要添加什么配置
从源“null”访问“http://localhost:49313/WebForm.aspx/GetData/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“Access-” Control-Allow-Origin'标头存在于请求的资源上。
首先,即使不发送数据,我也建议您始终使用POST。 Get 倾向于建议并“暗示”您正在调用 REST 端点。
因此,为了让您的代码正常工作,您需要将例程(实际上是相关网页的方法)标记/设置为静态。
所以,你需要这个:
[WebMethod]
public static string GetDate()
{
return "Hellow how are you";
}
因此,您需要将该例程定义为网络方法。
因此你发现你需要:
using System.Web.Services;
现在示例如下所示:
function mytest() {
$.ajax({
type: "POST",
url: "GuageTest2.aspx/GetData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyReturnData) {
alert("Return data = " + MyReturnData.d)
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
请非常仔细地注意,您必须使用“.d”来获取返回值(这是一个.net的东西,我相信这是一个安全问题,但“.d”是您获取返回值的方式)。
假设您想返回多个值?
然后我经常直接将一个类直接推入该页面后面的代码中。
这样说:
public class MyStatInfo
{
public int TotalFiles = 0;
public int PdfFiles = 0;
public int ZipFiles = 0;
}
[WebMethod]
public static MyStatInfo GetData()
{
MyStatInfo MyData= new MyStatInfo();
MyData.TotalFiles = 100;
MyData.PdfFiles = 75;
MyData.ZipFiles = 25;
return MyData;
}
现在JS代码是这样的:
success: function (MyStats) {
var TotalFiles = MyStats.d.TotalFiles
var PdfFiles = MyStats.d.PdfFiles
var ZipFiles = MyStats.d.ZipFiles
... do whatever with the value(s)
再次注意使用“.d”来获取返回的数据。