0

我正在尝试发送一个后请求并在回调的响应中有所不同。

function get_response() 
{
    var data = 
    {
        value1: "value1",
        value2: "value2"
    };          
    $.post("/index.php?id=1",data,function(text) 
        {
            $("#container1").empty();
            $("#container1").append(text);
            $("#container2").empty();
            $("#container2").append(text);
        });
        return;
}

我正在向我当前所在的页面发送两个值。每个值都被传递给不同的函数,每个函数我收到一个结果。

if (isset($_POST['value1']))
{
    echo $this->function_1();
    exit;
}

if (isset($_POST['value2']))
{
    echo $this->function_2();
    exit;
}

我已经尝试了很多并且用谷歌搜索了更多......但我找不到任何适合我情况的东西。我基本上想将function_1的返回值粘贴到#container1中,将function_2的返回值粘贴到#container2中。

我想我的大脑比我的问题 atm 的结构更混乱......但我希望它仍然可以理解(:

我目前运行 2 个不同的 post-functions,但是由于两者都设置为一个间隔,因此同时发送多个帖子让我很烦,我认为这是低效的(间隔很短,因此它可以叠加)。

4

2 回答 2

0

为什么不连接响应然后拆分它们?

$response="";
if (isset($_POST['value1']))
{
    $response.=$this->function_1();
}

if (isset($_POST['value2']))
{
    $response.='|'.$this->function_2();
}
echo $response;

在 Jquery 中:

function get_response() 
{
    var data = 
    {
        value1: "value1",
        value2: "value2"
    };          
    $.post("/index.php?id=1",data,function(text) 
        {
            var response=text.split("|");
            if (response.length==2){
            $("#container1").empty();
            $("#container1").append(response[0]);
            $("#container2").empty();
            $("#container2").append(response[1]);
        }
        });
        data = null;
        text = null;
        return;
}

选项 2 将是 JSON,正如 @subirkumarsao 所说:

$response=Array();
if (isset($_POST['value1']))
{
    $response['value1']=$this->function_1();
}

if (isset($_POST['value2']))
{
    $response['value2']=$this->function_2();
}
echo json_encode($response);

和jQuery:

function get_response() 
{
    var data = 
    {
        value1: "value1",
        value2: "value2"
    };          
    $.post("/index.php?id=1",data,function(text) 
        {
            var response=jQuery.parseJSON(text);
            if (response.length==2){
            $("#container1").empty();
            $("#container1").append(response.value1);
            $("#container2").empty();
            $("#container2").append(response.value2);
        }
        });
        data = null;
        text = null;
        return;
}

您应该始终尝试尽可能少的帖子,因为它的性能昂贵。

于 2012-07-10T09:02:17.580 回答
0

创建 JSON 响应。就像是

{
 "func1":"output of func1",
 "func2":"output of func2"
}

在ajax响应中你可以做到。

text.func1 // 将此设置为容器 1

text.func2 // 将此设置为容器 2

于 2012-07-10T09:05:00.010 回答