一个简单的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 + " " + result[i].name+"<br />";
}
$("#span1").append(html);
}
});
});
</script>
</head>
<body>
<span id="span1"></span>
</body>
</html>
jsonp调用效果如下:
ajax调用效果如下:
关键是:在API接口和AJAX调用的页面,双方都要约定一个参数名,如:callback ,这个参数名称可以改成其他的,但是API和AJAX必须一致,才能用。