简体   繁体   中英

Passing parameter to json_callback function

I am using an inverse geolocation method from mapquest that looks something like this

function fieldVia_changed(a)
            {
                if (document.getElementsByName("via"+a)[0].value.trim().length!=0)
                {
                   var via = document.getElementsByName("via"+a)[0].value ;
                   var strV = via.replace(/ |,/g, "+");
                   var s = document.createElement('script');     
                   s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q='+strV+'&json_callback=cbv&format=json&polygon=1&addressdetails=1';
                document.getElementsByTagName('head')[0].appendChild(s);
                }

            }

The results of the request are processed in the function cbv which accepts a parameter

 function cbv(json) 
            {
                v_lat[0] = json[0].lat;
                v_lng[0] = json[0].lon; 
             }

However i need to be able to pass another parameter to the cbv function from fieldVia_changed function so that i can process the information properly. The cbv function definition would look like this function cbv(json,a). I looked all over but i can not find a solution. Is it possible ?

The server side won't usually have the option of passing additional arguments in a JSONP system. A possible solution is to use the value of a in the callback function name, and dynamically create the function as a kind of man in the middle between the cbv() function, allowing you to pass a as a second argument.

function fieldVia_changed(a) {
    if (document.getElementsByName("via" + a)[0].value.trim().length != 0) {

        // dynamically create the function
        window['cbv_' + a] = function (json) {
            cbv(json, a);
        };

        var via = document.getElementsByName("via" + a)[0].value;
        var strV = via.replace(/ |,/g, "+");
        var s = document.createElement('script');
        // call the function cbv_x
        s.src = 'http://open.mapquestapi.com/nominatim/v1/search?q=' + strV + '&json_callback=cbv_' + a + '&format=json&polygon=1&addressdetails=1';
        document.getElementsByTagName('head')[0].appendChild(s);
    }
}

function cbv(json, a) {
    v_lat[0] = json[0].lat;
    v_lng[0] = json[0].lon;
    console.log(a);
}

This is OK if a is some sort of short identifier, if it's from user input then it's not really suitable for use in the function name. You're using in the name attributes so I'm assume this is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM