简体   繁体   English

将参数传递给json_callback函数

[英]Passing parameter to json_callback function

I am using an inverse geolocation method from mapquest that looks something like this 我正在使用来自mapquest的逆地理定位方法,看起来像这样

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 请求结果在接受参数的函数cbv中处理

 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. 但是我需要能够将另一个参数从fieldVia_changed函数传递给cbv函数,以便我可以正确处理信息。 The cbv function definition would look like this function cbv(json,a). cbv函数定义类似于此函数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. 服务器端通常不会选择在JSONP系统中传递其他参数。 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. 一种可能的解决方案是使用回调函数名称中的a值,并在cbv()函数之间的中间动态创建该函数,使其成为一种人,从而允许您将a作为第二个参数传递。

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. 如果a是某种短标识符,则可以,如果它来自用户输入,那么它实际上不适合在函数名称中使用。 You're using in the name attributes so I'm assume this is fine. 您正在使用name属性,因此我认为这很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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