开发者

web request from the user browser

is it possible to send a web re开发者_StackOverflowquest from the user browser to another api and then process the result sent back??

im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...

$(document).ready(function() {

        $.ajax({
            type: "GET",
            url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
            dataType: "xml",
            success: function(xml) {
                alert("sucess");
                $(xml).find('Ip').each(function() {
                    var ip = $(this).find('Ip').text();
                    alert(ip);

                });
            }
        });

    });


Due to same origin policy restriction you are pretty limited to sending AJAX requests to your own domain only. JSONP is a common workaround but the remote site needs to support it. Another workaround consists in crating a server side script on your domain which will serve as a bridge between your domain and the remote domain and it will simply delegate the AJAX request sent to it from javascript.


Should be possible, I have done the same.

BUT you have to have the pages on the same server, you cannot send a request to another server, in that case you would have to use a proxy on your server to relay the call.


Just to add to what was already said: if you can't create your own JSONP proxy, you can use YQL service which creates that proxy for you. Note that YQL will wrap your data with it's own meta data (unless there is a way yo disable that...).

By the way, you should use JSON output instead of XML output from your API service. JSON is a more lightweight format and as such is more adapted for Web.

Below is a fully functional example with your API URL (outputting JSON this time) and YQL:

var apiRequestUrl = "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=json";
var yqlRequestUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22";
yqlRequestUrl += encodeURIComponent(apiRequestUrl);
yqlRequestUrl += "%22&format=json&callback=?";

$.getJSON(yqlRequestUrl,
    function(jsonData) {
        alert(jsonData.query.results.json.Ip);
    });

Finally, this article can come handy: http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜