Skip to content

Knockoutjs: populate json url data to select options

Today this thing got me frustrated, let’s straight to the main problem, before I forget

  1. create js function to load from an URL contains json data
    define([
        'uiComponent',
        'ko',
        'jquery',
        'mage/translate',
        'Magento_Ui/js/modal/modal',
        'Magento_Checkout/js/model/quote',
        'mage/url'
    ], function (Component, ko, $, $t, modal, quote, url) {
        'use strict';
    
        var popUp = null;
        var jsonData = null;
    
        return Component.extend({
            ............
            getStoreList: function () {
    
                var somevar = url.build('someurl/madeyou/frustrated');
                var xmlHttp = new XMLHttpRequest();
                /* sample json data
                [{"id":"12","store_name":"blabla store 1"},
                 {"id":"13","store_name":"blabla store 2"}]
    
                */
                xmlHttp.open( "GET", somevar, false );
                xmlHttp.send( null );
                var resp = xmlHttp.responseText;
                return JSON.parse(resp);
    
            },
           .............
        });
    });

     

  2.  start binding here
    <select name="some-name" id="some-id" 
    data-bind="options: getStoreList(), 
    optionsText: 'store_name',
    optionsValue: 'id'" />

     

 

Comments are closed.