后端代码
public class JsonpTestController : Controller
{
// GET: JsonpTest
public void Index()
{
string strCallBack = Request["callback"];
var user = new
{
id = 1,
name = "小明"
};
string jsonResult = JsonConvert.SerializeObject(user);
HttpContext.Response.Write(jsonResult);
HttpContext.Response.End();
}
public void IndexJsonp()
{
string strCallBack = Request["callback"];
var user = new{
id =1,
name="小明"
};
string jsonResult = JsonConvert.SerializeObject(user);
HttpContext.Response.Write($@"{strCallBack}({jsonResult})");
HttpContext.Response.End();
//string strResult = CommonUtil.FormatJson_RegionList(oslt, "");
//string strCallBack = RequestProcess.RequestString("callback");
//if (strCallBack != "")
//{
// HttpContext.Current.Response.Write(strCallBack + "(" + strResult + ");");
// HttpContext.Current.Response.End();
//}
//else
//{
// HttpContext.Current.Response.Write(strResult);
// HttpContext.Current.Response.End();
//}
}
}
前端代码
<input type="button" id="getJsonp" value="访问Jsonp">
<input type="button" id="getJson" value="访问不带Jsonp">
<script>
//访问成功
$("#getJsonp").click(function(){
$.ajax({
url: 'http://localhost:52186/JsonpTest/IndexJsonp',
type: 'GET',
data: {},
dataType: 'JSONP',
success: function (res) {
debugger
},
error(xhr,status,error){
debugger
}
});
});
//访问失败
$("#getJson").click(function(){
$.ajax({
url: 'http://localhost:52186/JsonpTest/Index',
type: 'GET',
data: {},
dataType: 'JSONP',
success: function (res) {
debugger
},
error(xhr,status,error){
debugger
}
});
});
</script>