利用jQuery获取数据,JSONP

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

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

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

服务端:

 1 using Newtonsoft.Json;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 
 8 namespace Jsonp.Controllers
 9 {
10     public class JsonpGController : Controller
11     {
12         public ContentResult GetJson()
13         {
14             string callBack = Request["callback"];//接受一下回调函数
15 
16             return Content(callBack + "(" + JsonConvert.SerializeObject(GetPerson()) + ")", "application/json");//构造回调函数
17         }
18         private Person GetPerson()
19         {
20             return new Person() { Age = 25, Name = "贺晓冬" };
21         }
22     }
23     class Person
24     {
25         public string Name { get; set; }
26         public int Age { get; set; }
27     }
28 }

客户端:

@{
    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>

返回的数据:

谢谢你长得这么好看还来看我的博客!
原文地址:https://www.cnblogs.com/hexd1230/p/4372300.html