如何在等待用户输入时暂停jQuery .each()循环?

时间:2014-10-28 17:25:45

标签: javascript php jquery ajax sqlite

在继续迭代之前,我无法让jQuery .each loop等待用户输入。 这是我的代码(我已经评论过我想要发生的事情):

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="common_components.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="slider.css">

<?php
include_once 'common_components.php';
$query = $dbh->query("SELECT movies_dir FROM settings");
$row = $query->fetch(PDO::FETCH_ASSOC);
date_default_timezone_set('UTC');
echo "<title>Movie Scanner</title>";
?>
<script src="jquery.min.js"></script>
<script>
var retval = "not done";
function EnterManually() {
alert("Entering Data Manually"); //data has been entered manually so exit function & move ontop next index in loop in document.ready.
retval = "done";
}

function insertIntoDB(id,path) {
var request = $.ajax({
url: "update_movie.php?id="+id+"&path="+path,
type: "GET",            
dataType: "html"
});
request.done(function(data) {
if (data == 0) {
alert("Movie Succesfully Inserted"); //data has been entered sucessfully (update movie returns 0) so exit this function & search_file function & move ontop next index in loop in document.ready.
retval = "done";
}
else if (data == 1) {
alert("Unable to insert movie!"); //update_movie.php returns an error (returns 1), so exit this function but DON'T exit search_file function - wait for user to click on another set of details.
retval = "not done";
}
});
}
var files = <?php echo json_encode(preg_grep('/^([^.])/',scandir(realpath($row["movies_dir"]))))?>;
function Search_file(path) {
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","search_file.php?path="+path,false); //load search_file.php with movie
xmlhttp.send(); //send file off
$('#result').empty();   //clear div of content
document.getElementById("result").innerHTML=xmlhttp.responseText; //load output into page
}
</script>
</head>

<body>

<div id="result">
<script>
$(document).ready(function() {
$.each(files, function(key, value) {
Search_file("<?php echo addslashes(realpath($row["movies_dir"]))?>"+"\\"+value); //iterate to next item in array & run search_file function
});
});

</script>
</div>
</body>
</html>

基本上,&#39;文件&#39;变量包含文件路径的JSON数组。对于数组中的每个索引,Search_file function在该路径上运行,该路径应显示该文件的搜索结果列表 - 调用&amp;显示search_file.php页面。

当用户在显示的列表中单击任何这些结果时,它应该尝试将(通过InsertIntoDB函数调用update_movie.php文件)的记录插入到数据库中。

如果插入成功(update_movie返回0)(或触发EnterManually函数),则函数应全部退出,.each循环应移至下一次迭代,重新开始整个过程​​。

如果插入函数不成功(因此update_movie将返回1),则不会发生任何事情 - .each循环不应递增。相反,我们应该等待用户点击另一个结果。

目前,我无法让.each循环等到用户点击结果,它只是直接递增直到循环中的最后一项。

1 个答案:

答案 0 :(得分:0)

你可以一次浏览一个文件。

var index = 0;
$("#result").on("click", function(){
    Search_file("<?php echo addslashes(realpath($row["movies_dir"]))?>"+"\\"+files[index]);
    index++;
});

这个想法是每次你点击结果的div时它会加载下一个文件。我没有包含检查限制的代码等等。

相关问题