这是我的简单代码
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
我在这里向action.php发送请求
如果在action.php中我分别回显了两个变量。
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
所以问题是在ajax我有参数响应的功能。我将如何能够从PHP接收这两个变量并将其显示在不同的div中。 我希望你们帮助我。感谢。
答案 0 :(得分:4)
将回复发送为JSON。
在PHP中
$return = array( $return_value, $return_value2 );
echo json_encode($return);
在Javascript中
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
答案 1 :(得分:1)
你可以从行动中返回一个json
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
然后在你的js中,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
答案 2 :(得分:0)
您需要使用json_encode
才能获取多条记录或数据。
action.php的
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
然后在 JS
中读取变量dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
答案 3 :(得分:0)
您可以使用json_encode
创建一个对象,如:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
然后将dataType: 'json'
添加到您的ajax选项中。 response
然后将是一个对象:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
您可以使用以下方式访问特定值response.return_value2
并将它们分开。