问题
As I know using ajax you can send data to the server but I'm confused about sending an array to post using XMLHttpRequest
not any library like jQuery. My question is that, is that possible to send an array to php
using XMLHttpRequest
and how does jQuery
send an array to php, I mean does jQuery do any additional work to send an array to server (php $_POST) ?
回答1:
Well you cannot send anything but a string of bytes. "Sending arrays" is done by serializing (making string representation of objects) the array and sending that. The server will then parse the string and re-build in-memory objects from it.
So sending [1,2,3]
over to PHP could happen like so:
var a = [1,2,3],
xmlhttp = new XMLHttpRequest;
xmlhttp.open( "POST", "test.php" );
xmlhttp.setRequestHeader( "Content-Type", "application/json" );
xmlhttp.send( '[1,2,3]' ); //Note that it's a string.
//This manual step could have been replaced with JSON.stringify(a)
test.php:
$data = file_get_contents( "php://input" ); //$data is now the string '[1,2,3]';
$data = json_decode( $data ); //$data is now a php array array(1,2,3)
Btw, with jQuery you would just do:
$.post( "test.php", JSON.stringify(a) );
回答2:
That depends on the protocol you choose to package your data structure. The 2 most commonly used are XML and JSON. Both have ways to declare an array:
JSON: ['one thing', 'another thing']
XML: <things><thing name='one thing' /><thing name='another thing' /></things>
and neither will take any significant extra work by the server. In many cases it will actually reduce work since you don't need to use a naming convention to differentiate between them.
回答3:
You want to send a jSon object (which can be an array). Check this out if you are using php Send JSON data to PHP using XMLHttpRequest w/o jQuery.
More about jSon: http://json.org/
jQuery jSon sample: JQuery and JSON
来源:https://stackoverflow.com/questions/12096941/how-to-send-arrays-using-xmlhttprequest-to-server