Javascript 如何将json ajax请求发布到web API

Javascript 如何将json ajax请求发布到web API,javascript,asp.net-mvc,Javascript,Asp.net Mvc,我无法从服务器端获取json数据。脚本调用服务器方法,但没有返回json数据 $(document).ready(function() { $("#SendMail").click(function() { $.ajax({ url: "http://localhost:2457/SendMail/SendMail/", dataType: 'json', type: 'POST',

我无法从服务器端获取json数据。脚本调用服务器方法,但没有返回json数据

$(document).ready(function() {
    $("#SendMail").click(function() {
        $.ajax({
            url: "http://localhost:2457/SendMail/SendMail/",
            dataType: 'json',
            type: 'POST',
            data: "{htmlTemplate:" + "ABC" + "}",
            //crossDomain: true,
            //contentType: "application/json; charset=utf-8",
            success: function(data, textStatus, xhr) {
                console.log(data);
                alert('Successfully called');
            },
            error: function(xhr, textStatus, errorThrown) {
                // console.log(errorThrown);

            }
        });
    });
});

 Function SendMail(htmlTemplate As String) As String
      Dim fname As String = Request.Form("htmlTemplate1")
      Dim lname As String = Request.Form("lname")
      Dim cmdSendMail As New SendMailCommand()
      Return "A"
    End Function

$(文档).ready(函数(){
$(“#发送邮件”)。单击(函数(){
$.ajax({
url:“/SendMail/SendMail/”,
数据类型:“文本”,
键入:“POST”,
数据:JSON.stringify({htmlTemplate:“ABC”}),
//跨域:是的,
contentType:“应用程序/json;字符集=utf-8”,
成功:函数(数据、文本状态、xhr){
控制台日志(数据);
警报(“成功调用”);
},
错误:函数(xhr、textStatus、errorshown){
console.log(错误抛出);
}
});
});
});

您不需要
http://localhost:2457/ 
仅服务名称将足够提供
webapi
方法。webapi控制器默认以/api/{Controller}/{Action}开头的路由如果没有“”,则无法工作。可能是您的webapi正在不同的端口上运行
<script>
$(document).ready(function () {
        $("#SendMail").click(function() {
            $.ajax({
              url: '/SendMail/SendMail/', 
              dataType: 'text',
                  type: 'POST',
                  data:JSON.stringify({htmlTemplate: "ABC"}),
              //crossDomain: true,
              contentType: "application/json; charset=utf-8",
              success: function (data, textStatus, xhr) {
               console.log(data);
                   alert('Successfully called');
                },
                error: function (xhr, textStatus, errorThrown) {
                   console.log(errorThrown);
                }
            });
        });
    });
</script>