Send and Recive an array with jQuery Ajax
I want to send an array from main.html to test.php file and receive an other array from test.php , but it does not work.plz help me!
main.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="jquery/jquery-1.4.2.js"></script>
<script type="text/javascript"><!--
$(function () {
$('#Button1').click(function () {
var SendArrary = [];
SendArrary[0] = $('#Text1').val();
SendArrary[1] = $('#Text2').val();
SendArrary[2] = $('#Text3').val();
$.get('test.php',
SendArrary,
function (RecieveArray) {
$('#Text1').val(RecieveArray[0]);
$('#Text2').val(RecieveArray[1]);
$('#Text3').val(RecieveArray[2]);
},
alert("Ajax Done!!!")
)
});
});
--></script>
</head>
<body>
1<input id="Text1" type="text" /><br />
2<input id="Text2" type="text" /><br />
3<input id="Text3" type="text" /><br />
<input id="Button1" type="button" value="button" />
</body>
</html>
test.p开发者_开发知识库hp
<?php
$RecieveArray = $_GET['SendArrary'];
$RecieveArray[0] = $RecieveArray[0]."1";
$RecieveArray[1] = $RecieveArray[1]."2";
$RecieveArray[2] = $RecieveArray[2]."3";
print_r($RecieveArray);
?>
Lazy way:
jquery: http://api.jquery.com/jQuery.get/
var callback = function(data){
data = $.parseJSON(data);
// do stuff with data
}
$.get("test.php", {
array: SendArrary
}, callback);
php: http://www.php.net/manual/en/function.explode.php
$arr = explode(",", $_GET['array']);
Note: your response NEEDS to be valid JSON, like:
["one", "two", "three", 4]
With php: http://php.net/manual/en/function.implode.php
echo("[".implode(",", $yourArray)."]");
You might want to look into php JSON toolkits if you want to venture beyond sending and receiving arrays.
Not sure if the php code will work right away, I just looked it up in the manuals, might be an error here or there, but you should get the jest if your read the manual links.
精彩评论