利用jQuery获取数据,JSONP

时间:2022-08-22 20:42:56

最近工作用到了跨域请求,所以此文就有了,概念网上都有,就不细说了,直接来了。

看了一篇文章,说的是通过扩展让ASP.NET Web API支持JSONP,jsonp网上有很多的教程,js代码部分基本和网上的一致,但是有很多都没有服务端的代码,

我写一下我实现的方法,希望与博友共同进步。

服务端:

 using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Jsonp.Controllers
{
public class JsonpGController : Controller
{
public ContentResult GetJson()
{
string callBack = Request["callback"];//接受一下回调函数 return Content(callBack + "(" + JsonConvert.SerializeObject(GetPerson()) + ")", "application/json");//构造回调函数
}
private Person GetPerson()
{
return new Person() { Age = , Name = "贺晓冬" };
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}

客户端:

@{
Layout = null;
} <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function () {
$('#btn').one('click', function () {
$.ajax({
type: 'GET',
url: 'http://localhost:54406/JsonpG/GetJson',
dataType: 'jsonp',
success: callBack
});
})
})
function callBack(data)
{
$('#dv').find('p:first').text(data.Name);
$('#dv').find('p:last').text(data.Age);
}
</script>
</head>
<body>
<input type="button" id="btn" value="点我" />
<div id="dv">
<p></p>
<p></p>
</div>
</body>
</html>

返回的数据:

利用jQuery获取数据,JSONP