asp.net webapi jsonp demo

asp.net webapi jsonp demo
“ttt(0)”
“ttt(1)”
自己调用jsonp接口
<script>
7 //回调函数
8 function showData (result) {
9 var data = JSON.stringify(result); //json对象转成字符串
10 $(“#text”).val(data);
11 }
12
13 $(document).ready(function () {
14
15 $(“#btn”).click(function () {
16 //向头部输入一个脚本,该脚本发起一个跨域请求
17 $(“head”).append(“<script src=’http://localhost:9090/student?callback=showData’><\/script>”);
18 });
19
20 });
21 </script>
使用jquery jsonp方法
26 $.ajax({
27 url: “http://localhost:9090/student”,
28 type: “GET”,
29 dataType: “jsonp”, //指定服务器返回的数据类型
30 jsonpCallback: “showData”, //指定回调函数名称
31 success: function (data) {
32 console.info(“调用success”);
33 }
34 });
使用Controller的Action返回字符串类型,从从服务端返回的总是字符串,给字符串添加了双引号,所以在Jquery的jsonp返回函数中解析失败
[HttpGet]
public string TestTwo(string callback)
{
string json = “{‘name’:’张三’,’age’:’20’}”;
string result = string.Format(“{0}({1})”, callback, json);
return result;
}
[HttpGet]
public void TestThree(string callback)
{
string json = “{‘name’:’张三’,’age’:’20’}”;
string result = string.Format(“{0}({1})”, callback, json);
//使用当前HttpResponseBase输入结果
ReqHelper.resp.Write(result);
//在WebApi中需要手动输出缓存内容
ReqHelper.resp.End();
}
demo2
<script>
//jsonp
function ttt(result) {
if (result == 1) {
alert(“success”);
} else {
alert(“failed”);
}
}
$(document).ready(function () {
var appendHead = function (content) {
var htmlScript = “<script src=’http://localhost:1782/api/jsonpdemo/islogin2?username=” + content + “&callback=ttt’>”;
htmlScript += “<\/script>”;
$(“body”).append(htmlScript);
}
$(“body”).click(function () {
appendHead(“admin”);
})
})
</script>
后端
[HttpGet]
[Route(“api/jsonpdemo/islogin2”)]
public HttpResponseMessage IsLogin2(string UserName, string CallBack)
{
var result = string.Empty;
if (UserName.Equals(“admin”))
{
result = $”{CallBack}({1})”;
}
else
{
result = $”{CallBack}({0})”;
}
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, “text/plain”);
return resp;
}