简体   繁体   中英

Javascript Array from PHP

To update a Javascript Array ( eventDates ) I want to get the content via Ajax/PHP – sadly I don't get it to work. Anyone knows how the PHP output ( data ) hast to look, that I can work with it?

      $.ajax({
        type: "GET",
        url: "_ajax_registration.php?type=getDate&project="+val,
        data: "data",
        success: function(data){
            var eventDates = data;
        }
      });

      /*
      var eventDates = [{date: new Date(2014, 1-1, 28)}},
                {date: new Date(2014, 1-1, 18)},
                {date: new Date(2014, 6-1, 18)},];
      */


      function showEventDates(date) {
        for (var i = 0; i < eventDates.length; i++) {
            if (date.getTime() == eventDates[i].date.getTime()) {
                return [true, ''];
            }
        }
        return [false, ''];
      }

      $("#datepicker").datepicker("destroy");       
      $( "#datepicker" ).datepicker({       
        beforeShowDay: showEventDates

      }); 
      $( "#datepicker" ).datepicker( "refresh" );   

You have an excrescent bracket after the first and an redundant comma on the last object. Try this:

 var eventDates = [{date: new Date(2014, 1-1, 28)},
            {date: new Date(2014, 1-1, 18)},
            {date: new Date(2014, 6-1, 18)}];

What I like to to is, on the php side, take your array and

echo json_encode($myArray));

then, in the jquery you canjust:

$.GetJson('ajax_reg.php', { type : 'getDate', project': val }, function(data) {
    eventDates = date;
});

You need to echo json_encode($someArray) from _ajax_registration.php .

Also, you won't be able to access eventDates outside of your ajax callback. You'll need to do:

function showEventDates(date) {
  for (var i = 0; i < eventDates.length; i++) {
    if (date.getTime() == eventDates[i].date.getTime()) {
      return [true, ''];
    }
  }
  return [false, ''];
}

$.ajax({
  type: "GET",
  url: "_ajax_registration.php?type=getDate&project="+val,
  success: function(data){
    var eventDates = data;
    $("#datepicker").datepicker("destroy");       
    $( "#datepicker" ).datepicker({       
      beforeShowDay: showEventDates
    }); 
    $( "#datepicker" ).datepicker( "refresh" );
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM