Jquery Ajax 跨域之JSONP方式极简示例,服务端是.net的ashx

来源:互联网 发布:淘宝生活网 编辑:程序博客网 时间:2024/06/04 19:30

使用JQuery Ajax的JSONP方式跨域访问是非常简便了,缺点是只能使用GET方式,而且灵活性非常差。

稍作小结:

原理:其实是JQuery利用HTML标签<script>可以跨域的这一特性演变而来,所以必须应用JQuery

缺点:只能get并且调用极为不灵活,易产生全局变量

有点:实现起来简单,且无需复杂配置服务器端。

废话不多说上代码

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title>    <script src="../LIB/JQuery/jquery-1.8.2.min.js"></script>    <script type="text/javascript">        function callback(obj) {           alert(JSON.stringify(obj));        }        function test() {            $.ajax({                url: "http://192.168.1.101/CommonAshx/JSONP.ashx",                //async: false,                type: 'GET',                cache: false,                //jsonp:"callback",//这里默认是callback代表回调函数名,实际可以自己换名字                dataType: 'jsonp'//here            });        }    </script></head><body>    <input type="button" value="test" onclick="test()" /></body></html>

<%@ WebHandler Language="C#" Class="DownLoad" %>using System;using System.Web;using System.IO;public class DownLoad : IHttpHandler{    public void ProcessRequest(HttpContext context) {        //context.Response.ContentType = "text/javascript";        string ss="{ \"asda\": 456}";        context.Response.Write("callback(" + ss + ")");    }    public bool IsReusable    {        get        {            return false;        }    }}


0 0
原创粉丝点击