2012-07-10 57 views
0

我試圖發送一個post-request並且在回調的響應中有所不同。分離Jquery Post的響應

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中。

我想我的大腦比大氣壓我的問題的結構更加搞砸了......但我希望它仍然是有點理解(:

我目前運行2個不同崗位的功能,但由於兩者都設置在一段時間內,我很討厭同時發送多個帖子,但在我看來效率很低(間隔很短,因此可能會疊加)。

回答

0

爲什麼不連接響應,然後拆分它們嗎?

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

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

而在Jqu紅黴素:

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; 
} 

你應該總是試圖儘可能少的帖子爲可能的,因爲它的性能昂貴。

+0

YEPP,工作...可以很容易的sooo有時-.-」我嘗試以不同的方式是相同的,但我用Typo3的主要函數中的變量對它進行了過度操作(不是在說這個,它只是髒代碼..) - 是的,我想將我的腳本從2個帖子減少到1個,以便更有效率地的性能(: – 2012-07-10 09:10:00

+0

儘管使用了選項1 – 2012-07-10 09:11:39

0

創建JSON響應。 類似於

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

在ajax響應中,您可以執行此操作。

text.func1 //將其設置爲container1

text.func2 //將其設置爲container2的