2012-05-25 51 views
0

我一直在搜索这个美妙的信息网站,但没有找到我正在寻找什么,只是零碎。从php/sql查询/ JSON查询创建jquery变量

对于整个JavaScript语言/ jQuery库来说相当新颖,但我开始越来越喜欢它,用它可以做的事情越来越多。

我有一个文件,array.php,打印出json格式化变量与某些日期,我想在.datepicker日历中禁用。

我已经得到了整个工作,除了从sql部分的变量。

这工作:var $BadDates = new Array("2012-05-28","2012-05-29","2012-05-30");

我想什么是这样的:

$.getJSON('array.php', function(data) { 
var $BadDates = []; 
} 

我array.php:

$query = "SELECT * FROM dates"; 
$query_result = mysql_query($query) or die(mysql_error()); 

$results = array(); 


while($row = mysql_fetch_assoc($query_result)) { 



    $n["startdate"] = $row['startdate']; 


    array_push($results, $n); 
} 
print json_encode($results); 

这就是我要完成(我知道它的全部错误,只是让我可以展示我的想法):

$BadDates = new Array("$.getJSON('array.php')"); 

已经检查出很多解决方案没有任何运气...

我欣赏所有我能得到的帮助!

/奥斯卡

回答

0

没有必要在这里使用AJAX,但我会告诉你两种方式:

首先,因为你的PHP文件打印JSON编码字符串,你可以只包括它在那里需要在你的PHP生成的页面:

<?php 
    /* Some php */ 
?> 

<!-- some html --> 

<script type="text/javascript"> 
    var badDates = <?php include('array.php'); ?>; 
    /* do something with badDates, which is now a JS array */ 
</script> 

<!-- some more html --> 

<?php 
    /* Some more php */ 
?> 

这将输出类似:http://codepad.org/4xHlcwig

对于AJAX检索阵列,你会:

<script type="text/javascript"> 
    $.ajax({ 
     url: '/array.php', 
     dataType: 'json', 
     success: function (data) { 
      /* data contains a JS array which was outputted from your file and decoded by jQuery for you */ 
     } 
    }); 

    /* -OR- your shorthand method */ 

    $.getJSON('array.php', function(data) { 
     /* data contains a JS array which was outputted from your file and decoded by jQuery for you */ 

    } 
</script>