2

I have a problem when passing data in .getJSON. The reason for this is because I need to pass variables with same name. So, I have a client in python and I do this with that code :

query_args = { 'name':[var1,var2,var3] }

output = urllib2.urlopen('http://'+servername+':'+port+'/'+action,urllib.urlencode(query_args,doseq=True))

if i try to do that in javasctipt with .getJSON, i try to do

$.getJSON(
    "http://servername::8001/SearchNode",
    {
        name: "name",
        name: "google"
    },
    function(data) {

        $.each(data, function(key, val) {
            console.log(key);
            console.log(val);
        });
    }   
);

When I debug query string I see only one of the variables. Can anyone give me a simple solution to my problem?

Regards

1
  • Another nice question. And ah, surprise, you just reached upvote levels ;-) Commented Dec 6, 2017 at 15:40

1 Answer 1

2

To pass multiple objects within one variable you must use another structure. In your case you want both the string name and google to be sent. By using your method you simply override the value of the variable name.

There are multiple ways to solve this problem. I must say, that I haven't used python for a while now (So phytoneers out there, feel free to correct me).

idea 1: Rename parameters in js-code and glue them together in python. Change one key of your 2 parameters, so they don't override...

$.getJSON(
    "http://servername::8001/SearchNode",
    {
        name1: "name", 
        name2: "google"
    },
    function(data) {...}
) 

...and afterwards rebuild your array...

query_args = {'name': [name1, name2] }

or alternatively don't bother with query_args, but rather handle them directly into your urllib.urlencode

output = urllib2.urlopen('yoururl', urllib.urlencode({'name':[name1, name2]}, True))

idea 2: This is probably what you want to do. Put both strings inside an array and sent this as a parameter. At json.org you can have a look at different kinds of datastructures send via ajax. In this case, your code would look like this:

$.getJSON(
    "http://servername::8001/SearchNode",
    {
        name: ["name", "google"]
    },
    function(data) {...}
) 

Using this method, you can easily add even more parameters, without adding so many different variables that you need to concat later. Since I'm not that familiar with python anymore, I can't tell you how python will store this (probably a list). But either way, you should be able to handle this as well into the urlencode function. (At least the documentation says, it must be a sequence, which this list certainly is)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.