Javascript 向脚本添加多个AJAX调用

Javascript 向脚本添加多个AJAX调用,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我需要在脚本中添加一个函数来获取当前服务器时间 我使用下面的PHP文件以毫秒为单位获取服务器时间 <?php date_default_timezone_set('Europe/London'); $serverTime = round(microtime(true) * 1000); echo json_encode($serverTime); ?> 现在我想删除该行并添加我的ajax请求 我已尝试将以下代码添加到脚本中,但无法使其执行 function now () {

我需要在脚本中添加一个函数来获取当前服务器时间

我使用下面的PHP文件以毫秒为单位获取服务器时间

<?php
date_default_timezone_set('Europe/London');
$serverTime = round(microtime(true) * 1000);
echo json_encode($serverTime);
?>  
现在我想删除该行并添加我的ajax请求

我已尝试将以下代码添加到脚本中,但无法使其执行

function now ()
{
    this.ajax.open('GET', 'serverTime.php',
                   true);
    this.ajax.send(null);       

    if (this.ajax.readyState != 4) return;
    if (this.ajax.status == 200)
    {
        // get response
        var now = eval ('('+this.ajax.responseText+')');
    }
}
最终结果是变量“NOW”包含serverTime.PHP的输出

这是我的脚本,我试图以各种方式添加另一个ajax get请求,但我无法使其正常工作

$.ajaxSetup({
    type: 'GET',
    headers: { "cache-control" : "no-cache" }
});

var PlayList = function (onUpdate, onError)
{
    // store user callbacks
    this.onUpdate = onUpdate; 
    this.onError  = onError;

    // setup internal event handlers
    this.onSongEnd = onSongEnd.bind (this);

    // allocate an Ajax handler
    try
    {
        this.ajax = window.XMLHttpRequest
            ? new XMLHttpRequest()
            : new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    {
        // fatal error: could not get an Ajax handler
        this.onError ("could not allocated Ajax handler");
    }
    this.ajax.onreadystatechange = onAjaxUpdate.bind(this);

    // launch initial request
    this.onSongEnd ();

    // ------------------------------------------
    // interface
    // ------------------------------------------

    // try another refresh in the specified amount of seconds
    this.retry = function (delay)
    {
        setTimeout (this.onSongEnd, delay*5000);
    }

    // ------------------------------------------
    // ancillary functions
    // ------------------------------------------

    // called when it's time to refresh the playlist
    function onSongEnd ()
    {
        // ask for a playlist update
        this.ajax.open('GET', 'playlist.php', // <-- reference your PHP script here
                       true);
        this.ajax.send(null);       
    }

    // called to handle Ajax request progress
    function onAjaxUpdate ()
    {       
        if (this.ajax.readyState != 4) return;
        if (this.ajax.status == 200)
        {
            // get response
            var list = eval ('('+this.ajax.responseText+')');

            // compute milliseconds remaining till the end of the current song
            var start = new Date(list[0].date_played.replace(' ', 'T')).getTime();  
            var now   = new Date (                                    ).getTime();
            var d = start - now + 6500
                  + parseInt(list[0].duration);
            if (d < 0)

            {
                // no new song started, retry in 3 seconds
                d = 3000;
            }
            else
            {
                // notify caller
                this.onUpdate (list);
            }

            // schedule next refresh
            setTimeout (this.onSongEnd, d);

        }
        else
        {
            // Ajax request failed. Most likely a fatal error
            this.onError ("Ajax request failed");
        }       
    }
}

var list = new PlayList (playlistupdate, playlisterror);

function playlistupdate (list)
{
for (var i = 0 ; i != list.length ; i++)
    {
        var song = list[i];

    }
{

    document.getElementById("list0artist").innerHTML=list[0].artist;
    document.getElementById("list0title").innerHTML=list[0].title;
    document.getElementById("list0label").innerHTML=list[0].label;
    document.getElementById("list0albumyear").innerHTML=list[0].albumyear;
    document.getElementById("list0picture").innerHTML='<img src="/testsite/covers/' + list[0].picture + '" width="170" height="170"/>';

    document.getElementById("list1artist").innerHTML=list[1].artist;
    document.getElementById("list1title").innerHTML=list[1].title;
    document.getElementById("list1label").innerHTML=list[1].label;
    document.getElementById("list1albumyear").innerHTML=list[1].albumyear;
    document.getElementById("list1picture").innerHTML='<img src="/testsite/covers/' + list[1].picture + '" width="84" height="84"/>';

    document.getElementById("list2artist").innerHTML=list[2].artist;
    document.getElementById("list2title").innerHTML=list[2].title;
    document.getElementById("list2label").innerHTML=list[2].label;
    document.getElementById("list2albumyear").innerHTML=list[2].albumyear;
    document.getElementById("list2picture").innerHTML='<img src="/testsite/covers/' + list[2].picture + '" width="84" height="84"/>';

    document.getElementById("list3artist").innerHTML=list[3].artist;
    document.getElementById("list3title").innerHTML=list[3].title;
    document.getElementById("list3label").innerHTML=list[3].label;
    document.getElementById("list3albumyear").innerHTML=list[3].albumyear;
    document.getElementById("list3picture").innerHTML='<img src="/testsite/covers/' + list[3].picture + '" width="84" height="84"/>';

    document.getElementById("list4artist").innerHTML=list[4].artist;
    document.getElementById("list4title").innerHTML=list[4].title;
    document.getElementById("list4label").innerHTML=list[4].label;
    document.getElementById("list4albumyear").innerHTML=list[4].albumyear;
    document.getElementById("list4picture").innerHTML='<img src="/testsite/covers/' + list[4].picture + '" width="84" height="84"/>';

$('.nowPlayNoAnimate').each(function() {
    $(this).toggleClass('nowPlayAnimate', $(this).parent().width() < $(this).width());
});

}
}

function playlisterror (msg)
{
    // display error message
    console.log ("Ajax error: "+msg);

    //retry
    list.retry (10); // retry in 10 seconds
}
$.ajaxSetup({
键入:“GET”,
标头:{“缓存控制”:“无缓存”}
});
var PlayList=函数(onUpdate,onError)
{
//存储用户回调
this.onUpdate=onUpdate;
this.onError=onError;
//设置内部事件处理程序
this.onSongEnd=onSongEnd.bind(this);
//分配一个Ajax处理程序
尝试
{
this.ajax=window.XMLHttpRequest
?新的XMLHttpRequest()
:新的ActiveXObject(“Microsoft.XMLHTTP”);
}
捕获(e)
{
//致命错误:无法获取Ajax处理程序
this.onError(“无法分配Ajax处理程序”);
}
this.ajax.onreadystatechange=onAjaxUpdate.bind(this);
//启动初始请求
this.onSongEnd();
// ------------------------------------------
//接口
// ------------------------------------------
//在指定的秒数内尝试另一次刷新
this.retry=函数(延迟)
{
设置超时(this.onSongEnd,延迟*5000);
}
// ------------------------------------------
//辅助功能
// ------------------------------------------
//在刷新播放列表时调用
函数onSongEnd()
{
//请求播放列表更新

this.ajax.open('GET','playlist.php',//为什么不使用jquery方法

function getServerTime() {
  var now = null; 
  $.ajax({
    url: "serverTime.php",
    dataType: 'JSON',
    async: false,
    success: function (data) {
      now = data;
    }
  });
  return now;
}
您可以通过浏览器便携方式启动任意数量的请求

附言: 您可能还想替换
document.getElementById(“list4artist”).innerHTML=list[4].Artister;

缩短
$(“#list4artist”).html(列表[4].artist);


编辑:添加
async
参数,使执行等待ajax调用模拟非异步函数调用。

假设您的服务返回日期对象,您需要在success函数内添加以下行(由Clément Prévost建议):

success函数是一个异步回调函数,在服务器返回值后触发。
您应该阅读Jquery Ajax,它将使您的生活更加轻松。

您发布的代码功能正常,您正在尝试添加另一个调用?您可以发布您尝试的内容吗?@Joe T由于知识贫乏,我已经添加了我一直在使用的NOW函数,我不知道如何将其添加到m的脚本中使用NOW变量读取结果。
function getServerTime() {
  var now = null; 
  $.ajax({
    url: "serverTime.php",
    dataType: 'JSON',
    async: false,
    success: function (data) {
      now = data;
    }
  });
  return now;
}
var now = data;