我想定期对服务器进行AJAX调用,服务器脚本(PHP)应该创建一个新的XML文件。然后,XML文件由另一个javascript函数读取并显示在网页上。我该如何做到这一点? 继承了我的Jquery代码:
setInterval(
function(){
$.Ajax({url: 'register.php'});}, 5000
);
正在请求的PHP代码:
session_start();
$user = $_SESSION['username'];
$uID = $_SESSION['UserID'];
$host="127.0.0.1:3306";
$db_name='wf_db';
$tbl_name="tasks";
$connect = new mysqli("$host","root"," ","$db_name")or die('Can\'t connect to database!');
$sql = "SELECT * FROM $tbl_name WHERE UserID='$uID' and Task_Completed='0'";
$query_data = mysqli_query($connect,$sql)or die('Couldnt get data');
$row = mysqli_num_rows($query_data);
chmod("result".$uID.".xml", 0755);
if($row != 0){
$file = fopen("result".$uID.".xml",'w')or die("Cannot Open File");
$_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
$_xml .="<tasks>\r\n";
while ($result = mysqli_fetch_array($query_data)) {
if ($result["TaskID"]) {
$_xml .="\t<task>\r\n";
$_xml .="\t\t<AssignDate>" . $result["Assign_Date"] . "</AssignDate>\r\n";
$_xml .="\t\t<TaskID>" . $result["TaskID"] . "</TaskID>\r\n";
$_xml .="\t\t<TaskSubject>" . $result["Task_Subject"] . "</TaskSubject>\r\n";
$_xml .="\t\t<Notes>" . $result["Notes"] . "</Notes>\r\n";
$_xml .="\t</task>\r\n";
} else {
$_xml .="\t<task title=\"Nothing Returned\">\r\n";
$_xml .="\t\t<AssignDate>none</Assign_Date>\r\n";
$_xml .="\t\t<TaskID>none</TaskID>\r\n";
$_xml .="\t\t<TaskSubject>none</TaskSubject>\r\n";
$_xml .="\t\t<Notes>none</Notes>\r\n";
$_xml .="\t</task>\r\n";
}
}
$_xml .="</tasks>";
fwrite($file, $_xml);
fclose($file);
}
else {
echo 'Oops something went wrong!';
}
这是我到目前为止,我错过了什么? 我是PHP和AJAX的新手,因此代码中可能存在错误。
答案 0 :(得分:1)
尝试使用setTimeout JS函数进行调用。
var T = setTimeout("myAjaxFunction");
function myAjaxFunction(){
//do what you want.
$.ajax({...});
}
答案 1 :(得分:0)
像
一样进行ajax调用setInterval(
function(){
$.ajax({
url: 'register.php',
type:'GET',
dataType:'text/xml',
success:function(xml){
//here is your xml sent from the server
//parse it using $.parseXML
//then manipulate it according to your will
},
error:function(jxhr){//error handler that will be called if something goes wrong
console.log(jxhr.responseText);
}//error handler ends
});//ajax call ends
}, 5000);
这里有一些你必须研究的有用链接
Using jQuery to parse XML returned from PHP script (imgur.com API)