Is there any way to use the JQuery GetJSON method

2019-03-03 08:47发布

问题:

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

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

I understand that because of the same-origin principle, this request will fail because the URL is an external domain.

However I've heard that GetJSON() does not obey this principle and can send asynchronous get requests to external servers using JSONP and an appended URL.

My question is: is it possible to use GetJSON() to retrieve all the HTML from an external name as a single string within a JSON object? If it doesn't do so by default, is there any way I can force / trick it into doing so?

回答1:

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.



回答2:

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.



回答3:

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"));
        }
    }