尝试使用 GET 请求调用方法 \u0027GetNextImage\u0027,这是不允许的

JIt*_*dra 4 jquery

我的客户端脚本中有一个 Web 方法 GetNextImage。在 ASPX 页面中我有以下代码。

function slideshow() {
  $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: "/RollingScreen.aspx/sample",
    dataType: "json",
    data: "{}",
    success: function (data) {
      //this changes the image on the web page
      $('#imgSlideShow').attr("src","~/Images/1.png");

      //fires another sleep/image cycle
      setTimeout(slideshow(), 5000);
    },
    error: function (result) {
      alert(result.message);
    }
  });
}

$(document).ready(function () {
  //Kicks the slideshow
  slideshow();
});
Run Code Online (Sandbox Code Playgroud)

我收到如下错误。

{"Message":"An attempt was made to call the method \u0027GetNextImage\u0027 using a GET request, which is not allowed.","StackTrace":" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} 
Run Code Online (Sandbox Code Playgroud)

请任何人都可以帮助我。提前致谢。

小智 5

向您的 WebMethod 添加属性以指示使用 HTTP GET。

[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static string sample()
{
   //Your Code Which Gets Next Image 
}
Run Code Online (Sandbox Code Playgroud)

您不应该使用 POST 而不是 GET。

“POST 请求无法添加书签、通过电子邮件发送或以其他方式重复使用。它们使用浏览器的后退/前进按钮搞砸了正确的导航。仅使用它们以一种独特的操作将数据发送到服务器,并且(通常)具有服务器通过重定向进行应答。” - deceze (使用 POST 而不是 GET 有什么不好的地方吗?