Get data from PHP array via AJAX and jQuery
I have a page as below:
<head>开发者_如何学Python;
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#prev').click(function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(result) {
$('#content1').html(result[0]);
},
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td id="prev">prev</td>
<td id="content1">X</td>
<td id="next">next</td>
</tr>
</table>
</body>
and a php file ajax.php
to handle ajax requests as;
<?php
$array = array(1,2,3,4,5,6);
echo $array;
?>
But when I click, I am getting A
instead of array[0]. How can I fix this?
you cannot access array (php array) from js try
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>
and js
$(document).ready( function() {
$('#prev').click(function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
$('#content1').html(result[0]);
},
});
});
});
quite possibly the simplest method ...
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
When you echo $array;
, the result is Array
, result[0]
then represents the first character in Array
which is A
.
One way to handle this problem would be like this:
ajax.php
<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
echo $a.",";
?>
jquery code
$(function(){ /* short for $(document).ready(function(){ */
$('#prev').click(function(){
$.ajax({type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data){
var tmp = data.split(",");
$('#content1').html(tmp[0]);
}
});
});
});
you cannot access array (php array) from js try
<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>
and js
$(document).ready( function() {
$('#prev').click(function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data) {
result=data.split('~');
$('#content1').html(result[0]);
},
});
});
});
When you do echo $array;
, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.
You might actually need
echo json_encode($array);
This should get you what you want.
EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)
精彩评论