【问题标题】:Asp.net Web API giving error in ajax callAsp.net Web API 在 ajax 调用中给出错误
【发布时间】:2013-03-15 23:53:07
【问题描述】:

我已经创建并托管了 ASP.NET Web API 服务。当我检查 Fiddler 时,该服务运行良好,但是当我通过 jQuery ajax 调用该服务时,它不起作用,我也没有收到任何错误。 我尝试调用不同的 API 方法,但遇到了同样的问题

WebAPI:

namespace WebApi.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public string Post(Interview Interview)
        {


            return "Date: " + Interview.DateOfSurvey + " \n rdInterviewObtained: " + Interview.rdInterviewObtained + "\n txtWhowasinterOther: " + Interview.txtWhowasinterOther;
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

Ajax 调用:

$("#btnSave2").click(function () {
var person = { DateOfSurvey: '01-01-2012', rdInterviewObtained: 'N', txtWhowasinterOther: 'N' };
alert('inside button click');
jQuery.support.cors = true;

        $.ajax({
            url: "http://url/api/Values",
            type: 'GET',
            //data: person,
            //dataType: 'json',
            success: function (data) {
                alert('success');

            },
            error: function (x, y, z) {
                alert('error');
                alert(x + '\n' + y + '\n' + z);
            }
        });
});

【问题讨论】:

  • 它不起作用并且您没有收到任何错误?好吧,成功或错误回调必须触发。 fiddler 对您的 ajax 请求有何看法?
  • 在 Chrome 中打开控制台,看看是什么错误。
  • 您收到“成功”警报还是“错误”警报?如果两者都不是,您可能会在 ajax 调用之前出错。
  • 它进入错误功能,但没有得到任何错误响应......我也尝试过 Post 但那也不起作用

标签: jquery asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您似乎在某个按钮的 .click 处理程序中调用了此 AJAX 方法。如果这是一个提交按钮,请确保您通过从回调中返回 false 来取消默认操作,否则您的 AJAX 调用可能永远没有时间执行。

您的代码的另一个问题是您已指示 jQuery 使用 CORS,但要使其正常工作,您需要 Web API 发送正确的响应标头。这是您可能会读到的an article,它说明了如何在服务器上实现这一点。

jQuery.support.cors = true;

$('#btnSave2').click(function () {
    $.ajax({
        url: 'http://url/api/Values',
        type: 'GET',
        success: function (data) {
            alert('success');
        },
        error: function (x, y, z) {
            alert('error');
            alert(x + '\n' + y + '\n' + z);
        }
    });

    return false;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2013-04-24
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多