我创建了一个validation_php它将返回
{"exists":false,"data":"", "id":101}
或
{"exists":true,"data":"www.example.com/thumbnail1.jpg", "id":101}
脚本如下
//no need to continue if there is no value in the POST username
if(!isset($_POST['id']))
exit;
$var = $_POST['id'];
//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=HOST;dbname=DBNAME','USER','PASS',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//prepare our query.
$query = $db->prepare('SELECT * FROM cont_pic WHERE pic_id = :id');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':id', $var);
//execute the query
$query->execute();
$exists = $query->fetchColumn(6);
//return the json object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => !empty($exists), 'data' => $exists, 'id' => $var ));
// echo $var;
print_r($exists);
?>
现在我已经完成了一半的JQuery投票脚本,我需要帮助使这个脚本工作。基本上我想要的是,如果存在是真的,我需要用一个等于json响应的id替换图像,并用响应中的数据替换img src,并停止民意调查。如果为假,继续轮询。
setInterval(function(){
$.ajax({ url: "validation.php", success: function(data){
}, dataType: "json"});
}, 30000);
多谢! !
var poller = setInterval(function(){
$.ajax({ url: "validation.php", success: function(data){
if (data.exists) {
clearInterval(poller);
$("#img"+data.id).attr("src", data.data);
}
}, dataType: "json"});
}, 30000);