有没有办法使用JQuery GetJSON方法从外部页面获取HTML?

所以,假设您正在尝试执行jquery ajax请求,例如:

$.ajax({ ... url: http://other-website.com ... }) 

我理解,由于同源原则,此请求将失败,因为URL是外部域。

但是我听说GetJSON()不遵守这个原则,可以使用JSONP和附加的URL向外部服务器发送异步get请求。

我的问题是:是否可以使用GetJSON()从外部名称检索所有HTML作为JSON对象中的单个字符串? 如果它默认不这样做,有什么办法可以强制/欺骗它这样做吗?

是的,您可以从远程位置请求html,但是您必须使用代理来执行此操作。 一个公开可用的代理是YQL。

http://jsfiddle.net/BKJWu/

 var query = 'SELECT * FROM html WHERE url="http://mattgemmell.com/2008/12/08/what-have-you-tried/" and xpath="//h1" and class="entry-title"'; var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=??"; $.getJSON(url,function(data){ alert(data.query.results.h1.content); }) 

你当然可以在你的服务器上构建自己的,返回普通的html而不是json。

答案是否定的,你不能欺骗它或强迫它从外部源加载html。 GetJSON仅适用于为JSONP提供服务的服务器,并且只能读取有效的JSON对象。

您可以使用GetJSON检索您有权访问的任何JSON对象。 这是Razor MVC控制器的一个例子。

jQuery代码

 $(function () { $.getJSON('@Url.Action("GetColorsJson", "Json")', function (jsonData) { var css = new customContentJs.css.apply(jsonData); }); }); 

控制器代码

 using System.Web.Mvc; using DAL; using Newtonsoft.Json; public class JsonController : Controller { private readonly CustomContentContext _db = new CustomContentContext(); ///  /// Return a json serialized object of user saved colors ///  ///  public string GetColorsJson() { return JsonConvert.SerializeObject(_db.Site.Include("Colors")); } }