Shopify getJSON API调用以获取countryCode

时间:2016-04-06 13:40:37

标签: javascript jquery json api shopify

我试图通过对[http://ip-api.com/json][1] [1]:http://ip-api.com/json进行JSON调用来从IP地址返回国家/地区代码,然后我想将货币代码写入一个cookie,然后更新整个网站的货币。

我目前的代码如下(HTML和CSS来自jsfiddle而不是代码的一部分),它适用于jsfiddle,但我似乎无法让它在Shopify上的商店中运行。



$.getJSON('http://ip-api.com/json', function (location) {

    if (location.countryCode == 'AU') {
       $('#currencies').text("AUD");
        Currency.cookie.write('AUD');
        Currency.convertAll(Currency.currentCurrency, 'AUD');
    }
     else {
       $('#currencies').text("EUR");
        Currency.cookie.write('EUR');
        Currency.convertAll(Currency.currentCurrency, 'EUR');
    }
});

body {
    font-size: 75%;
    font-family:"Segoe UI", Verdana, Helvetica, Sans-Serif;
}
#body {
    clear: both;
    margin: 0 auto;
    max-width: 534px;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
    margin-top: 0.75em;
    border: 0 none;
    margin-top:35px;
}
#body td {
    padding:15px 30px 15px 10px;
}
#body tr td:nth-child(1) {
    font-weight:bold;
}
#address {
    width:400px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body">
    <table border="1">
        <tr>
            <td>Currency:</td>
            <td id="currencies"></td>
        </tr>
    </table>
</div>
&#13;
&#13;
&#13;

这是我第一次用JS编写代码并进行JSON调用,所以我不太确定在Shopify中使用jQuery时是否存在语法错误或其他问题? 感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我不确定.text是否有效。试试这个

$.getJSON('http://ip-api.com/json', function (location) {
    if (location.countryCode == 'AU') {
       $('#currencies').html('AUD');
        Currency.cookie.write('AUD');
        Currency.convertAll(Currency.currentCurrency, 'AUD');
    }
     else {
       $('#currencies').html('EUR');
        Currency.cookie.write('EUR');
        Currency.convertAll(Currency.currentCurrency, 'EUR');
    }
});

另外,恕我直言localStorage是更好的Cookie选择。 - http://www.w3schools.com/html/html5_webstorage.asp

从评论中的讨论更新:

$.getJSON('https://geoip.nekudo.com/api/', function (location) {
    if (location.country.code == 'AU') {
       $('#currencies').val('AUD');
        Currency.cookie.write('AUD');
        Currency.convertAll(Currency.currentCurrency, 'AUD');
    }
     else {
       $('#currencies').val('EUR');
        Currency.cookie.write('EUR');
        Currency.convertAll(Currency.currentCurrency, 'EUR');
    }
});