What is the best way to send PHP array via jquery?
can anybody help to explain or give reference on how to send array of mu开发者_运维百科ltiple array (or just array ) in jquery. and what the best way to do when something is failed or successfull. what i mean is how the php code send back the success or failed message
See this article for an example. Basically, you have to use PHP's json_encode()
to convert a PHP array to JSON code. In the linked example, the jquery-json plugin is used to convert JSON back to a Javascript array.
Alternatively, you can use jQuery's built-in capabilities for retrieving a PHP response as a Javascript array/object.
Use JSON ENCODE
Something like this:
index.php
<script type="text/javascript" src="jsfile.js"></script>
<a href='numbers.php' class='ajax'>Click</a>
numbers.php
<?php
$arr = array ( "one" => "1", "two" => "2", "three" => "3" ); // your array
echo json_encode( $arr ); // encode it to json
?>
jsfile.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
alert(snippets); // your array in jquery
});
});
});
If it is a simple error message and always the same one, you can simply return that string e.g. "error" and test for that value in JavaScript. But I would recommend to send the complec data in XML or even better in JSON (because it is smaller and can be used without poarsing it in JavaScript). Just do this in your PHP:
if($error){
echo "error";
} else {
json_encode($complex_data);
}
If you want to put some information into your error, which I highly recommend, just return an error array encoded with JSON. So replace the echo "error" with this:
echo json_encode(array("error" => "your error message", "status" => "an optional error status you can compare in JavaScript"))
Than you just have to check if the "error" is found in the JSON returned from PHP.
精彩评论