0

json (IP DATA) を取得し、AJAX を使用してデータ (GEO IP) を取得する Javascript を作成しようとしています。

$(document).ready(function(){
    var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
    $.ajax({
        url: path_to_the_webservice,
        success: function(html)
        {
            if(html)
            {
                alert('3');
                $('#content').append(html);                         
            }
            else
            {
                alert('4');
            }
        }
    });
});

そして、アラート(4)が表示されます。なぜですか?

基本的にhttp://www.pathtothescript.com/check.php、ブラウザからアクセスすると、解析する必要がある JSON を取得します

$.getJSON(path_to_the_json,
function(data) 
{
    $.each(data, function(i,item)
    {

    });
}

しかし、私はそれを作る方法がわかりません。

jsonはこんな感じhttp://j.maxmind.com/app/geoip.js

何か助けはありますか?ありがとう!

4

1 に答える 1

0

Same origin policyが原因である可能性があります。

JSONP リクエストを使用してみてください:

$.getJSON('http://example.com?callback=?', function(data) {
    console.log(data);
});

http://j.maxmind.com/app/geoip.jsからの応答の処理

// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {

    console.log('Retrieved data:',
                data,
                'is type of', typeof data);

    // Now we have some functions to use:
    console.info('Some info:', geoip_country_name(),
                geoip_latitude(),
                geoip_longitude());
});​

フィドル


アップデート:

チャットで、前の例は Google Chrome では問題なく動作するが、Mozilla Firefox では動作しないことがわかりました。少し遊んで解決策を見つけましたが:

// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
    url: 'http://j.maxmind.com/app/geoip.js',
    type: 'GET',
    success: function(data) {
        // Now we have some functions to use:
        alert(geoip_country_name() + ': (' 
              + geoip_latitude() + '; ' 
              + geoip_longitude() + ')');
    },
    error: function(e) {
        console.log('Error:', e);
    },
    contentType: 'application/javascript; charset=ISO-8859-1',
    dataType: 'script'
});

</p>

Fiddleまた、サービスドキュメント
に応じて文字セットを設定しました。

于 2012-10-21T21:25:31.603 に答える