jQuery的Ajax调用WEB API [英] Jquery Ajax Call to WEB API

查看:173
本文介绍了jQuery的Ajax调用WEB API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的jQuery ajax调用到Web API方法。

I'm trying to make a simple jquery ajax call to a WEB API method.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script type="text/javascript">

    $(document).ready(function () {

        $.ajax({
            type: 'POST',
            url: 'http://redrock.com:6606/api/values/get',

            dataType: "jsonp",

            crossDomain: true,
            success: function (msg) {

                alert("success");

            },
            error: function (request, status, error) {

                alert(error);
            }
        });
    });

</script>

WEB API操作:

WEB API action:

 public IEnumerable<string> Get()
  {
     return new string[] { "value1", "value2" };
  }

Ajax调用不打的WEB API。我得到在浏览器控制台下面的错误。

ajax call does not hitting the WEB API. I get the below error in browser console.

GET <一href="http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850" rel="nofollow">http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400(错误请求)

GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400 (Bad Request)

推荐答案

您还没有包括在code的路线设置,但假设它是正确的,问题是由事实,你有一个名为可能引起您的WebAPI方法获取您尝试使用POST请求来打一段时间。这是因为的WebAPI试图找出HTTP动词从动作的名称。

You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.

我会建议要么重命名操作或添加 [HttpPost] 属性为您的操作方法。你也可以试试<一href="http://blogs.msdn.com/b/webdev/archive/2013/04/04/debugging-asp-net-web-api-with-route-debugger.aspx"相对=nofollow> WebApiRouteDebugger 包。

I would suggest either renaming the action or adding the [HttpPost] attribute to your action method. You may also try the WebApiRouteDebugger package.

这篇关于jQuery的Ajax调用WEB API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆