8

我不明白为什么以下代码在 FF 中可以完美运行,但在 IE9 中却不行。

该脚本的作用是,在单击按钮时,它会从表单中选择一些值,例如街道、邮政编码和城镇,构建一个字符串,将其提交给 google,然后返回该地址的纬度和经度(并将其分为两个表格中的字段)

$("#google_coordinates").live("click", function(){

    var string = encodeURIComponent($('#sAddressStreet1').val())+",";
    if($('#sAddressStreet2').val() != ""){
        string += encodeURIComponent($('#sAddressStreet2').val())+",";
    }
    string += encodeURIComponent($('#sAddressPostalcode').val())+",";
    string += encodeURIComponent($('#sAddressTown').val())+",";
    string += encodeURIComponent($('#sAddressCountryCode option:selected').text());

/* test with an alert - string shows fine in both FF and IE */    
    alert(string);

    $.get("http://maps.googleapis.com/maps/api/geocode/xml?address="+string+"&sensor=false", function(xml){
       $(xml).find('location').each(function() {
           lat = $(this).find('lat').text();
           lng = $(this).find('lng').text();

/* test with an alert - fine in FF not in IE */    
alert(lat + ',' + lng);

               $("#sAddressLatitude").val(lat);

           $("#sAddressLongitude").val(lng);
       });
    });

    return false;
});

在这种情况下,此脚本提交的 url 是:=1363342459585">http://maps.googleapis.com/maps/api/geocode/xml?address=Servicev%C3%A4gen%207,311%2033,Falkenberg,Sweden&sensor=false& =1363342459585

我尝试将缓存更改为 false,使用 $.ajax 而不是 $.get 通过放入一些警报进行测试,但我似乎无法进入 $.get 函数

I've tried changing the MIME type as is suggested here http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests, but that didn't help eather.

Any ideas anyone?

EDIT: Even tried with json result from google, to see if the problem lies in the XML, but that does not work either.

$.ajax({
    type: "GET",
    url: "http://maps.googleapis.com/maps/api/geocode/json?address="+string+"&sensor=false",
    dataType: "json",
    cache: false,
    success: function(json){
        alert("hiero");
        lat = json.results[0].geometry.location.lat;
        lng = json.results[0].geometry.location.lng;

        $("#sAddressLatitude").val(lat);
        $("#sAddressLongitude").val(lng);
    }
});
4

2 回答 2

6

Because you're performing a cross-domain request, the browser needs to support this. Most modern browsers (like FF and Chrome) support it, but IE9 only supports it when specific requirements are met.

Here's what Microsoft has to say about it, including some pointers on how to get it working (provided all the requirements as mentioned on the Microsoft page can be met).

于 2013-03-17T12:43:42.407 回答
1

Did you try setting crossDomain to true in your $.ajax params?

Check the reference here for the crossDomain:bool param: http://api.jquery.com/jQuery.ajax/

It should work seamlessly between browsers.

Edit

After checking jQuery's source, seems there's no mention of XDomainRequest (the way ie8/9 support CORS), so I'm not sure it works. Otherwise, if you really want to support those, make a wrapper around $.ajax with XDomainRequest if browser == ie9 or ie8.

于 2013-03-23T17:40:32.850 回答