![](/img/trans.png)
[英]Is There any way to do the same role that the method .load() in jquery does to get part of html page with vanilla Javascript
[英]Is there any way to use the JQuery GetJSON method to get HTML from an external page?
因此,假设您正在尝试执行jquery ajax请求,例如:
$.ajax({
...
url: http://other-website.com
...
})
我了解由于同源原则,该请求将失败,因为URL是一个外部域。
但是,我听说GetJSON()
不遵循此原理,可以使用JSONP和附加的URL向外部服务器发送异步get请求。
我的问题是:是否可以使用GetJSON()
从外部名称作为JSON对象中的单个字符串检索所有HTML? 如果默认情况下不这样做,我有什么办法可以强迫/欺骗它呢?
是的,您可以从远程位置请求html,但是必须使用代理进行请求。 YQL是一个公开可用的代理。
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();
/// <summary>
/// Return a json serialized object of user saved colors
/// </summary>
/// <returns></returns>
public string GetColorsJson()
{
return JsonConvert.SerializeObject(_db.Site.Include("Colors"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.