【问题标题】:Post Ajax call says Get not allowed发布 Ajax 调用说不允许获取
【发布时间】:2017-08-08 02:46:43
【问题描述】:

我正在尝试将 ajax 与 post 方法一起使用,但它一直弹出我这个错误

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

这里是js

var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
    method: "POST",
    url: "ContactUs.aspx/SendEmail",
    contentType: "application/json; charset=UTF-8",
    data: json,
    dataType:"json",
    success: function (data) {
        var a = 3;
    },
    error:function(a,b){
        var a = 43;
    }
})

这里是c#的服务器端

[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}

提前致谢!

【问题讨论】:

  • 您使用的是 .asmx 还是 web api?
  • 其中的一个
  • sendEmail 是某个 .aspx 页面代码后面的方法吗?
  • 是的。我什至尝试添加 `[ScriptMethod(UseHttpGet = false)]` 但没有成功
  • 不,你不能这样做,最好添加.asmx文件,在那里写方法,然后用jquery调用。

标签: javascript c# jquery ajax


【解决方案1】:

您应该遵循以下方式: 您已经使用[WebMethod] 装饰并添加了using System.Web.Services; 引用的后端方法,我已更改方法以返回某些内容,以便验证它是否有效。

[WebMethod]
public static String sendEmail(string param)
{
 return "Your String";
}

在您的 .aspx 页面中,添加 scriptManager 以启用客户端调用您的代码背后的方法

<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

最后在你的JQuery script 中,调用这样的方法:

$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
  alert(response);
}});

希望对你有帮助!

【讨论】:

  • 非常感谢!但是你知道为什么它被认为是get吗?
【解决方案2】:

尝试使用 [HttpPost] 而不是 [WebMethod] 并删除静态。 它是 REST API 还是 MVC?

【讨论】:

  • 首先考虑到 .aspx 页面扩展和 [WebMethod] 的使用,推测它是 WebForms 是合理的。因此 WebAPI 的 [HttpPost] 在这里不适用。
  • 可能是其他人?
猜你喜欢
  • 2016-10-19
  • 2023-03-26
  • 1970-01-01
  • 2019-07-29
  • 2017-12-15
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 2015-11-25
相关资源
最近更新 更多