使用jquery自动完成获取数据属性

时间:2018-03-25 17:39:51

标签: javascript jquery ajax autocomplete custom-data-attribute

需要从Mapbox API获取额外的数据属性。

这是我使用的自动完成插件。 https://xdsoft.net/jqplugins/autocomplete/

(Python / Django后端)

基本上,我想通过ajax调用将国家代码,城市,国家等其他数据推送到我的数据库。

$("#hometown").autocomplete({

    dropdownWidth:'auto',
    appendMethod:'replace',
     valid: function () {
        return true;
 },
    source: [
        function (query, add) {
        var country;
        var suggestions = [];
        var result = {};
            // console.log(query);
            var url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + encodeURIComponent(query) + '.json?access_token=pk.eyJ1Ijoicm9uYWxkbDkzIiwiYSI6ImNqZjAzaHgyeDBmbDUzM3BjdmlwcDcxZzgifQ.dFh3sKokufA_VwGiIE9QFQ&types=region,place&language=en-ZA';
            $.getJSON(url, function (resp) {

                console.log("API CALL SUCCESS");
                for (var i = 0; i < resp.features.length; i += 1) {
                    // console.log(resp.features[i].context[1]["text"]);
                   suggestions.push({"value": resp.features[i]['place_name'], "country": resp.features[i].context[1]["text"], "city": resp.features[i]["text"] });
                    country = resp.features[i].context[1]['text'];
                    // console.log(suggestions);

                 }

                 result["suggestions"] = add(suggestions);
                console.log(suggestions);
                add(suggestions);
                // console.log(suggestions)


            })
        }],
     getTitle:function(item){

        return item['value']
  // return '<div class="active" id="#homecountry-data" data-value="'+ item['value'] +'" data-country="'+ item['country'] +'" data-city="'+ item['city'] +'" style="display: none"></div>';
 },
});

很多评论只是我试验并试图弄清楚哪些有效,哪些无效。

这大致是我对ajax调用的想法。

$("#updatesettings").click(function() {
    console.log("I clicked")
    var home = $('#hometown').val();

        var settingsdata = {

            'home': home,
    };

        console.log(settingsdata);

    $('#updatesettings').prop('disabled', true);
    if (home.length >0){
        // $("#loader").show();
        ajaxCall('/modsettings', settingsdata,
            function(data){
            var succ = data.ok;
            if(succ == 'ok'){
                // $("#feedbackpopup").hide();
                alert("Settings Updated");
                // $('#contactName, #contactEmail, #contactMessage').val('');
                $('#updatesettings').prop('disabled', false);
            }

            if(succ == 'no'){
                alert("Oops. That didn't work. If this error continues please screenshot this and send me a message and I will fix it asap");
             $('#updatesettings').prop('disabled', false);
            }
        }
        );
    }
    else{
        $('#updatesettings').prop('disabled', false);
        alert("Please make sure all fields are complete.");
    }
});

一旦我工作,我将重置api密钥。 :)

1 个答案:

答案 0 :(得分:0)

我最终这样做了。

// AUTOCOMPLETE TRY 2

var city;
var country;
var long;
var lat;
var citysettings

// autocomplete with help from Pietz. DANKJEWEL!!!
$(function() {
 $('#hometown').autocomplete({
    minChars: 3,
     lookup: function (query, done) {
         // console.log(query);
         var result = {};
         var suggestions = [];
         // console.log(result)

         $.ajax({
             type: 'GET',
             //CORS-enabled API
             url: "https://api.mapbox.com/geocoding/v5/mapbox.places/" + encodeURIComponent(query) + ".json?access_token=pk.eyJ1Ijoicm9uYWxkbDkzIiwiYSI6ImNqZjAzaHgyeDBmbDUzM3BjdmlwcDcxZzgifQ.dFh3sKokufA_VwGiIE9QFQ&types=place&language=en-ZA",

             dataType: "json",

             success: function (json) {
                 console.log("API call successful.");

                 for (var i = 0; i < json.features.length; i += 1) {
                  console.log(json.features[i]['place_name']);
                  try {
                        suggestions.push({
                            "value": json.features[i]['place_name'],
                            "country": json.features[i].context[1]['text'],
                            "city": json.features[i]['text_en-ZA'],
                            "long": json.features[i].center[0],
                            "lat": json.features[i].center[1]
                        });

                    }
                    catch(err) {

                      suggestions.push({
                            "value": json.features[i]['place_name'],
                            "country": json.features[i].context[0]['text'],
                            "city": json.features[i]['text_en-ZA'],
                            "long": json.features[i].center[0],
                            "lat": json.features[i].center[1]
                        });


                    }

                   // var country = json.features[i].context[1]['text'];
                   // var city = json.features[i]['text'];
                   // long = json.features[i].center[0];
                   // lat = json.features[i].center[1];
                   // console.log(lat);
                 }
                 result["suggestions"] = suggestions;
                 done(result);
                 console.log(result);


                 // $('.autocomplete.suggestions').click(function () {
                 //     console.log(onclick);
                 //     console.log(country);
                 // });


             },


             error: function (ajaxContext) {
                 console.log(ajaxContext.responseText)
             }

         });

     },
         onSelect: function (suggestion) {
        city = suggestion.city;
        country = suggestion.country;
        long = suggestion.long;
        lat = suggestion.lat;

                citysettings = {
          "city": city,
          "country": country,
          "long": long,
          "lat": lat
    };

    },



     lookupLimit: 1

 });
 });

        $("#updatesettings").click(function () {

        console.log(citysettings);

});