Is there any way to use the JQuery GetJSON method to get HTML from an external page?

前端 未结 3 563
野趣味
野趣味 2021-01-26 04:11

So let\'s say you\'re trying to do a jquery ajax request, something like:

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

I under

相关标签:
3条回答
  • 2021-01-26 04:21

    You can retrieve any JSON object that you have access to with GetJSON. Here is an example with Razor an MVC Controller.

    jQuery Code

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

    Controller Code

    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"));
            }
        }
    
    0 讨论(0)
  • 2021-01-26 04:39

    Yes, you can request html from a remote location, however you must use a proxy to do so. One publicly available proxy is 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);
    })
    

    You could of course build your own on your server that returns plain html rather than json.

    0 讨论(0)
  • 2021-01-26 04:45

    The answer is no, you cannot trick it or force it to load html from an external source. GetJSON only works on servers that serve JSONP, and only valid JSON objects are able to be read.

    0 讨论(0)
提交回复
热议问题