[英]Sending an array of objects to PHP function with jQuery.ajax request
有這樣的對象數組:
rectangle[0].width = w;
rectangle[0].height = h;
rectangle[1].width = w;
rectangle[2].height = h;
rectangle[3].width = w;
rectangle[3].height = h;
...
我們如何通過jQuery.ajax請求將此數組發送到PHP函數,反之亦然,如何將來自PHP函數的修改數組作為響應? 我認為JS代碼可能是:
request = $.ajax({
type : "POST",
url : "post.php",
data : {rec :rectangle}
});
request.done(function(msg) {
alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
和PHP:
if (isset($_POST["rec"]) {
$rec = $_POST["rec"];
$arr_length = count($rec);
$response = $arr_length;
}
echo $response;
請證明請求的真實形式。 謝謝。
很容易:
<script>
var myarray = new Array();
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
$.post(
'test.php',
{ data: paramJSON },
function(data) {
var result = JSON.parse(data);
}
</script>
php side:
if(isset($_POST["data"]))
{
$data = json_decode($_POST["data"]);
$myarray = $data->myarray;
foreach($myarray as $singular)
{
// do something
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.