2012-12-03 65 views
1

通常當我想在一個PHP文件中創建新的內容和地方實現它在我的地盤我做這樣的事情(JS和PHP):發送多個PHP文件與AJAX

case 'someCasename': 
    ... 
    include_once 'file.php'; 
    break; 

... 
success: function(data){ 
    $("#idSelector").html(data); 
} 

和新內容顯示在選定的元素上。

但我很好奇,如果它可能發送多個php文件在同一時間。不知道這是否真的有必要,而且我還沒有碰到過需要這樣做的單一時間,但我想到了這一點,並想問一問。這最後的代碼是最有可能非常非常錯誤的,但我只是想展示我的意思:

case 'someCasename': 
... 
$phpArray = array("file1" => include_once 'file1.php', "file2" => include_once 'file2.php', "file3" => include_once 'file3.php'): 
echo $phpArray; 
break; 

... 
success: function(data){ 
    $("#idSelector").html(data.file1); 
    $("#idSelector").html(data.file2); 
    $("#idSelector").html(data.file3); 
} 

是這樣的,即使remotly可能嗎?你不能json_encode php文件可以嗎?

+0

查看jQuery的load()方法。 http://api.jquery.com/load/ –

回答

1

如果我正確理解你的話,你包含的php文件會回顯出你想在ajax調用的成功函數中使用的東西。

你可以做什麼,循環遍歷所有包含,並使用輸出緩衝來捕獲這些文件在數組中的輸出。

喜歡的東西:

case 'someCasename': 
    ... 
    $results = array(); 
    while (files_to_include) 
    { 
    ob_start; // start output buffering 
    include_once "your_file"; 
    $results[] = ob_get_clean(); // get the contents of the output buffer 
    } 
    echo json_encode($results); // send all collected output as json to be used on the js side 
    break; 

雖然這會工作,當然,這將是更好的使用你的,而不是包括返回值的功能。

+0

沒關係,所以在另一端我會檢索這樣的文件:\t成功:function(data){ \t \t var imported = $ .parseJSON(data); \t \t $(「#idSelector」)。html(imported.file1); \t \t $(「#idSelector」)。html(imported.file2); \t \t $(「#idSelector」)。html(imported.file3); \t} – user1683645

+0

@ user1683645這是一般的想法。 – jeroen