一个简单的jQuery+AJAX+JSONP解决跨域调用的问题

一个简单的jQuery+AJAX+JSONP解决跨域调用的问题

直接上代码:

ashx页面,作为api接口,返回一个json:

<%@ WebHandler Language="C#" Class="jsonp" %>

using System;
using System.Web;

public class jsonp : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        
        string json = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";
        if (!string.IsNullOrEmpty(context.Request["callback"]))
        {
            context.Response.Write(string.Format("{0}({1})", context.Request["callback"].Trim(), json));
        }
        else
        {
            context.Response.Write(json);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

json效果如下:

html页面,jQuery+ajax 跨域调用以上接口:

<!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 type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            $.ajax({
                type: "GET",
                dataType: "jsonp",
                jsonp: "callback",
                jsonpCallback:"user",
                url: "http://webtest.demo.com/api/jsonp.ashx",
                data: {},
                success: function (result) {
                    var html = "";
                    for (var i in result) {
                        html += result[i].id + "&nbsp;" + result[i].name+"<br />";
                    }
                    $("#span1").append(html);
                }
            });
        });
    </script>
</head>
<body>
    <span id="span1"></span>
</body>
</html>

jsonp调用效果如下:

ajax调用效果如下:

关键是:在API接口和AJAX调用的页面,双方都要约定一个参数名,如:callback ,这个参数名称可以改成其他的,但是API和AJAX必须一致,才能用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值