Multiple AJAX responses
I have a page where a user can "view more info", an ID is sent to a php page which then queries the database. It then returns some data, with some of the data I want to put this into a textarea, the other into a standard div.
How can I send multiple responses back, and how do I know what the data is? e.g. send name and address, how do I know what the php page is sending back so that I can interpret the data on client side?
Is there a better way than using
httpxml.responseText.indexOf("something")
As the two responses开发者_开发问答 may contain similar data? What I hope to do is send two variables from the PHP page and then "see" these variables on client side?
Hope I haven't made this too confusing, thanks.
Javascript only please.
Return JSON containing all your values from the PHP. Then after getting the response your javascript can do whatever you'd like to do with the values.
http://www.php.net/manual/en/function.json-encode.php
--PHP--
$responseArr = array('a'=>1, 'b'=>2);
echo json_encode($responseArr);
If I remember correctly (i do this with jQuery now), just performing eval() on your response text will form the object for you.
--javascript-- (just vanilla js right? you didnt mention jQuery or anything) this is probably inside your onreadystatechange block
var r = xhr.responseText; //assuming you name the XMLHttpRequest object 'xhr'
var rlist = eval('('+r+')');
document.getElementByID("foo").innerHTML = rlist['a']; //or whatever you want to do with these
document.getElementByID("bar").innerHTML = rlist['b'];
精彩评论