开发者

Best strategy on sending an array with AJAX

I have some checkboxes to send to the server as array. Usually, I have the list of these checkboxes and I send it through an array[].

For example, submitting this :

<input type="checkbox" class="linkStyle" name=开发者_运维技巧"style[]" value="1" checked="checked" /> 1
<input type="checkbox" class="linkStyle" name="style[]" value="2" checked="checked" /> 2
<input type="checkbox" class="linkStyle" name="style[]" value="3" checked="checked" /> 3

i'll send to the server these parameters :

style[]=1
style[]=2
style[]=3

on server side, using PHP, I can get this array using $_POST['style'] (it put these parameters automatically into an array);

Now, doing it with an AJAX request, the scenario it's a bit strange, because using the function serialize() for example I don't get the same result : in fact, it put in a single variable the whole string, and it doesnt send theme values as distinct parameters.

Referring to the example before, it will send somethings like :

style: style%5B%5D=Style1&style%5B%5D=Style2&style%5B%5D=Style3

and this is uncomfortable on PHP, because it doesnt create an array for this values. So i've done my own script that emulate this behaviour. such as :

var styles="";
$('.linkStyle:checked').each(function(i,el){
    styles=styles+'style[]='+$(this).val()+'&';
});

$.ajax ({
    url: "list/browse_ajax.php",
    type: "POST",
    data: styles+'&id=browseUpdate&actualArtist='+browseArtist+'&actualEvent='+browseEvent+'&actualDate='+browseData,
    success: function(data) {
        $('#browseList').html(data);
    },
    error: function(data) {
        $('#browseList').html("Error");
    }
});

Now, what I'd like to know, is :

  1. What do you think about this strategy?
  2. Is it better create a JSON object and manage it on client/server side (memory, processing, timing, resources, and so on)?
  3. Why, for stuff like this, should I create an object, convert it as json, decode it on php, manage result, convert it on json and resend? I can manage just a string...
  4. Only PHP or others language server side (like ASP?) create automatically the array from the list of parameters with same name and []?

Hope that my question is enough understandable :)


I think you're on the right track with JSON, it makes the most sense here.

  1. Serialize the form to JSON ( Serializing to JSON in jQuery )
  2. POST that JSON string via ajax
  3. Then http://php.net/manual/en/function.json-decode.php

Also see Convert form data to JavaScript object with jQuery (those two SO questions contain valuable links to libraries & plugins)

Edit

As for your questions:

What do you think about this strategy?

Your example shown? I'm assuming you've tested it & it works. If it emulates the behavior you've come to expect, I think it's just fine. It requires you to rewrite none of your PHP and it's something you obviously are comfortable working with. Those are benefits.

However, if you work judiciously, encoding your form input into JSON and using json_decode has the same effect, theoretically requiring very little change for you in the way you write your PHP after you've decoded the JSON.

Is it better create a JSON object and manage it on client/server side (memory, processing, timing, resources, and so on)?

I can't speak for memory etc. I wouldn't expect it to be bad for performance to deal with the JSON object on the server side. There's usually not a simple answer for questions like that, because it depends on too many other things.

Why, for stuff like this, should I create an object, convert it as json, decode it on php, manage result, convert it on json and resend? I can manage just a string...

What's happening in your example without JSON (loosely speaking):

  • Browser takes input, encodes it into a GET request string
  • Makes a GET request that includes the string
  • PHP accesses the GET string, allowing you to reference it as an array

What'll happen in your example with JSON (again, loosely speaking):

  • Your JavaScript takes input, encodes it into JSON
  • Makes a GET (or POST) request that includes the string
  • PHP accesses the GET string (or POST data), allowing you to reference it as an array
  • You use json_decode on one of the array keys to convert it into a PHP object

The way you phrased it gives me the impression you think using JSON is adding a lot of extra steps. I think the added complexity is largely imaginary. (Depending on how you choose to "serialize" the form input into JSON it may in fact really just be a JSON-valid string up until you decode with PHP.)

There would likely be future benefits to choosing to deal with the same JSON object all the time. Imagine sending validation information back & forth in JSON, for example...

Only PHP or others language server side (like ASP?) create automatically the array from the list of parameters with same name and []?

I'm not sure I understand this question, but I'd answer that how a language deals with a GET string encoded from:

<input name="style[]" />
<input name="style[]" />
<input name="style[]" />

Would be unique to the language. I've dealt with ColdFusion before and I wanted something sort of similar (to construct a struct based on the name of inputs). But to do it I had to loop through the FORM scope and "re-declare", even though it was valid dot syntax, ex:

<input name="name.first" />
<input name="name.middle" />
<input name="name.last" />

It's not like JavaScript, for example, should be expected to treat those inputs like an array. I don't recall JavaScript allowing you to populate an array with this syntax:

style[] = "red";
style[] = "green";
style[] = "blue";

Whereas PHP does. It's not like either one is doing anything wrong. It's a shortcut in PHP. The shortest way to populate an array in JavaScript is different.

And as for converting it to an array, well...You don't pass arrays in HTTP requests, PHP lets you access the GET string as an array (or the POST data) without you consciously having to do anything special...two different matters.

That's actually the most compelling reason to use JSON here, which is why the others have said that's exactly what JSON is meant for. Think about it, JSON is "a lightweight, language-independent, text-based open standard designed for human-readable data exchange." You represent arrays and objects with JSON that can always be accessed as arrays and objects no matter what language you choose to work with.


  1. To complex method to use.
  2. I would prefer JSON, it is far easier to use, and if you would like to change it someday it will be much easier. Also, if some other programmer needs to understand your code, he will probably understand JSON better :)
  3. I didn't understand the question.
  4. If you send the data by post it should be converted to an array by most languages.

Good luck!


To send an array from js.

var qry = new Object();
qry['arg1'] = ...
qry['arg2'] = ...
qry['arg3'] = ...

then

var jsonqry  = 'jsonqry=' + JSON.stringify(arg);

init your XMLHttpRequest ...

ajax.send(jsonqry);

To receive with php.

$jsonqry = $_POST['jsonqry'];
$json = json_decode($jsonqry);

then I have $json->arg1, etc.

The other direction:

in php:

$a = array();
$a['parm1'] = ...
$a['parm2'] = ...
$a['parm3'] = ...


var $rsp = json_encode($a);
echo $rsp;

and back in js, in the Ajax listener:

var rsp = JSON.parse(msg);

and I have

rsp.parm1, etc.

I think this is pretty much the conventional best practice, or close.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜