Multiple key/value pairs in HTTP POST where key is the same name

后端 未结 2 427
心在旅途
心在旅途 2020-12-17 00:04

I\'m working on an API that accepts data from remote clients, some of which where the key in an HTTP POST almost functions as an array. In english what this means is say I h

相关标签:
2条回答
  • 2020-12-17 00:52

    Send your data as XML or JSON and parse whatever you need out of it.

    0 讨论(0)
  • 2020-12-17 00:57

    There are two ways to handle this, and it's going to depend on your client-side architecture how you go about doing it, as the HTTP standards do not make the situation cut and dry.

    Traditionally, HTTP requests would simply use the same key for repeated values, and leave it up to the client architecture to realize what was going on. For instance, you could have a post request with the following values:

    student_name=Bob+Smith&student_name=Jane+Smith&student_name=Chris+Smith
    

    When the receiving architecture got that string, it would have to realize that there were multiple keys of student_name and act accordingly. It's usually implemented so that if you have a single key, a scalar value is created, and if you have multiples of the same key, the values are put into an array.

    Modern client-side architectures such as PHP and Rails use a different syntax however. Any key you want to be read in as an array gets square brackets appended, like this:

    student_name[]=Bob+Smith&student_name[]=Jane+Smith&student_name[]=Chris+Smith
    

    The receiving architecture will create an array structure named "student_name" without the brackets. The square bracket syntax solves the problem of not being able to send an array with only a single value, which could not be handled with the "traditional" method.

    Because you're using Rails, the square bracket syntax would be the way to go. If you think you might switch server-side architectures or want to distribute your code, you could look into more agnostic methods, such as JSON-encoding the string being sent, which adds overhead, but might be useful if it's a situation you expect to have to handle.

    There's a great post on all this in the context of JQuery Ajax parameters here.

    0 讨论(0)
提交回复
热议问题