2012-12-03 43 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