在AJAX处理后返回多变量php

时间:2017-02-13 15:29:08

标签: php ajax

我需要用Ajax返回来回答PHP处理 但我不知道如何改变两个变量

HTML

<html>
<head>
 <title>Sceener Ajax</title> 
 <script src="jquery.js"></script>
</head>
<body>


 <div id="name"></div>
 <div id="family"></div>



<script type="text/javascript">
$(document).ready(function(){
        $.ajax ({
            type: "POST",
            url: "ajax.php",
            success: function( result_1 ) {
                var name = result_1;
                $("#name").html(name);
            }
        });
});
</script>
</body>
</html>

ajax.php

<?php
$name = 'My Name';
$family = 'My Family';
echo ( $name );
?>

我该怎么做才能帮助我

4 个答案:

答案 0 :(得分:2)

将要返回的所有值放入数组中,将其编码为JSON,然后在javascript中将其读回:

所以PHP变成了

<?php
    $name = 'My Name';
    $family = 'My Family';
    $result = array ('name' => $name, 'family' => $family);
    echo ( json_encode($name ));
?>

你的javascript就像这样:

<script type="text/javascript">
$(document).ready(function(){
        $.ajax ({
            type: "POST",
            url: "ajax.php",
            success: function( result ) {
                var name = result.name;
                var family = result.family;
                $("#name").html(name);
            }
        });
});
</script>

答案 1 :(得分:2)

您应该返回一个json对象而不是字符串。

在PHP中,使用值创建一个数组并从中创建一个json字符串:

$response = [
    'name' => 'My Name',
    'family' => 'My Family'
];

// Encode the array as a json string
echo json_encode($response);

dataType: 'json'添加到a​​jax调用中,以使jQuery将响应解析为json对象,然后从中获取值:

$(document).ready(function(){
    $.ajax ({
        type: "POST",
        url: "ajax.php",
        dataType: 'json', // <-- This will make jQuery handle the json response correctly
        success: function( response ) {
            // Now you can get both values from the json object
            console.log(response.name);
            console.log(response.family);
        }
    });
});

答案 2 :(得分:1)

在PHP中创建一个包含所有数据的数组或对象

<?php
$reply['name'] = 'My Name';
$reply['family' = 'My Family';
// this will convert the array to a JSON String 
// for transmission to the browser
echo json_encode($reply);
?>

在你的javascript代码中期望返回一个对象

<script type="text/javascript">
$(document).ready(function(){
    $.ajax ({
            type: "POST",
            url: "ajax.php",
            dataType = 'json',      // tell jquery to expect a JSON String
                                    //and auto convert to a js object
            success: function( data ) {
                $("#name").val(data.name);
                $("#family").val(data.family);

            }
        });
});
</script>

答案 3 :(得分:0)

<?php $data['name']= 'My Name'; 
$data['family'] = 'My Family'; 
echo json_encode($data);
?>

你得到了json格式的答案。