这里的第一个脚本旨在获取静态.json文件以显示某些内容并为其设置动画。代码段是
var self = this;
$.getJSON('data/post_'+ index +'.json', function(d){
self.postCache[index] = d;
callback(d)
但我想将其修改为可以从数据库中获取数据。我得到的数据格式与静态json文件中的格式相同,我的问题是如何将该数据传递给此脚本,以便它能够正常工作。
我正在使用ajax发送请求
$(function ()
{
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
//I really dont know what to write here :(
}
});
});
并且api.php文件从数据库获取数据,我使用json_encode将数据编码为json
答案 0 :(得分:0)
$.getJSON
只需调用$.ajax
,并自动为您设置一些预定义值。这意味着,因为您说数据是相同的,所以您可以像以前一样完成相同的操作。
this
在成功功能中,保存您的引用并执行回调
var self = this;
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
self.postCache[index] = data;
callback(data);
}
});
答案 1 :(得分:0)
var self = this;
$.post('api.php',
{"post_id": index},
success: function(d)
{
self.postCache[index] = d;
callback(d);
});
请参阅http://api.jquery.com/jquery.post/
在api.php中做一个SQL查询,其中post_id = $ _POST ['post_id']然后回显json_encode($ database_row);