Cross-Domain request when server does NOT support

2019-04-16 06:45发布

问题:

Im trying to solve this problem for hours now. I got a wikia web which I want to get stuff from but it supports only json, not even xml or jsonp.

I tried everything. If I call it as jsonp my client returns error "SyntaxError: invalid label" cause the server doesnt return it as jsonp or json at all. If I add "callback=?" to the url and leave it as json, same error returned.

Here is part of my code (I modified it too many times and nothing worked so far)

$('#searchBox').keydown(function() {
    $.ajax({
        type: "GET",
        url: "http://leagueoflegends.wikia.com/index.php?callback=?",
        data: {
            action: "ajax",
            rs: "getLinkSuggest",
            format: "json",
            query: "jungl"
        },
        success: function(json){
            alert("Success");
        },
        error: function(){
            alert("Error");
        },
        dataType: "json"
    });
});

UPDATE Here is my solution, which works: (Using YQL)

    var url = "http://leagueoflegends.wikia.com/index.php?action=ajax&rs=getLinkSuggest&format=json&query=jung"
    url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=xml';
    $.ajax({
        type: "GET",
        url: url,
        success: function(text){
            text = text.split("<p>")[1].split("</p>")[0];
            alert(text);
        },
        error: function(){
            alert("Error");
        },
        dataType: "text"
});

回答1:

If the remote server doesn't support JSONP or allow CORS, then you'll have to bounce the request server-side to bypass the same-origin rule.



回答2:

you can't do crossdomain AJAX without JSONP or CORS.

Nevertheless you can code an HTTP proxy in backend to do request in backend instead of the user (= js).