您的位置:首页 > Web前端 > JQuery

ajax跨域系列--web api方式跨域

2016-03-29 16:11 543 查看
上一节讲到如何使用jsonp进行跨域请求api,这次我们用一些微软新的框架解决这个问题

web api是微软继web service ,wcf推出的新一代的服务提供框架

不多说了,用用看

首先一个基类,所有的controller继承此基类,里面有个无返回值的方法Options

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
public class ApiController : Controller
{
public string Options()
{
return null; // HTTP 200 response with empty body

}
}
}
我们的具体调用的action:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Filter;

namespace MvcApplication1.Controllers
{

public class HomeController : ApiController
{
public ActionResult Index()
{
return View();
}

public JsonResult Get()
{
IList<DataModel> ls=new List<DataModel>(){
new DataModel{
name="kong",
age=25
},
new DataModel{
name="wang",
age=26
}
};
return Json(ls, JsonRequestBehavior.AllowGet);
}
}

public class DataModel
{
public string name { get; set; }
public int age { get; set; }
}
}


在根目录下配置web.config里面的system.webServer节点,新增
<pre name="code" class="html"> <httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
</customHeaders>
</httpProtocol>
-------------------------------------------以上是webapi项目下面是调用者的前端页面:
<pre name="code" class="javascript"><script type="text/javascript">
$(function () {
$.ajax({
type: "get",
async: false,
url: "http://localhost:8/home/get",
dataType: "json",
success: function (json) {
var html = '<li class="swiper-slide tabNavActive">推荐</li>';
$.each(json, function () {
html += '<li class="swiper-slide">' + this.name + '</li>';
});
$("#floor").html(html);
},
error: function () {
alert('fail');
}
});
});
</script>
测试OK。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息