我有一个网站需要从使用asp.net MVC /
的不同网站获取一些数据要加载的数据来自这些页面:
http://charity.hondaclassic.com/home/totaldonations
http://charity.hondaclassic.com/Home/CharityList
这应该是一个没脑子但是由于某种原因我得到一个空的回答,这是我的JS:
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
$('.totalDonations').load('http://charity.hondaclassic.com/home/totaldonations');
$('#charityList').load('http://charity.hondaclassic.com/home/CharityList');
});
</script>
在firebug中我看到请求已经完成并返回200响应,但响应是空的,如果你浏览这些页面他们工作正常!到底是什么?
以下是MVC网站的控制器操作:
public ActionResult TotalDonations() {
var total = "$" + repo.All<Customer>().Sum(x => x.AmountPaid).ToString();
return Content(total);
}
public ActionResult CharityList() {
var charities = repo.All<Company>();
return View(charities);
}
有人请说出我错过了什么愚蠢的小事 - 这应该花了我5分钟,这已经是几个小时了!
答案 0 :(得分:2)
same origin policy阻止通过AJAX从其他网站加载HTML。执行此操作的正确方法是让方法检测请求是否来自AJAX并返回JSONP。
public ActionResult TotalDonations( string callback )
{
var total = "$" + repo.All<Customer>().Sum(x => x.AmountPaid).ToString();
if (!string.IsNullOrEmpty(callback))
{
return Content( callback + "( { total: " + total + " } );" );
}
else
{
return Content(total);
}
}
...
$.getJSON('http://charity.hondaclassic.com/home/totaldonations?callback=?',
function(data) {
$('.totalDonations').html( data.total );
});
答案 1 :(得分:0)
您的totaldonations链接总共缺少 o
> $('.totalDonations').load('http://charity.hondaclassic.com/home/ttaldonations');
应该是
$('.totalDonations').load('http://charity.hondaclassic.com/home/totaldonations');
答案 2 :(得分:0)
我最后只是做服务器端以避免上面提到的相同的原始策略:
Dim totalDonations As String
Dim charities As String
Using Client As New System.Net.WebClient()
totalDonations = Client.DownloadString("http://charity.hondaclassic.com/home/totaldonations")
charities = Client.DownloadString("http://charity.hondaclassic.com/home/CharityList")
End Using
像魅力一样工作。