0

我怎样才能把这个:

<? echo json_encode($myArrays); ?>

...进入这个:

_rowData: [
    { name: "Most Recent", view: "recentView" }, 
    { name: "Most Popular", view: "popularView" }, 
    { name: "Staff Picks", view: "staffView" }
],

我的脚本返回那个 ^,但我不知道如何将数据放入字符串中,_rowData?PS我正在使用Dashcode,试图将项目动态加载到列表控制器中

到目前为止,我有这个:

var recentListControllerXHR = $.ajax("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", function(data){
                            return(JSON.stringify(data));
                          }, 'text');

rowData: recentListControllerXHR,
4

5 回答 5

1

试试这个:

var rowData;
$.getJSON("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", function(data) {
    rowData = data;
});

但请注意,rowData在调用回调函数(参见调用的第二个参数)之前,它不可用getJSON

于 2009-12-28T18:23:17.013 回答
1

好的 - 您的问题似乎是对异步 API 如何工作的误解。$.ajax()发出请求,并在将来的某个时候使用响应调用提供的回调。

假设您有要填充的对象的名称,您可以使用以下内容填写所需的属性:

var someObject = {
  ...
  rowData: null,
  ...
};

// at this point, someObject is incomplete...

$.getJSON("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", 
  function(data)
  {
    // called whenever the server gets around to sending back the data
    someObject.rowData = data;
    // at this point, someObject is complete.
  });

请注意,我在这里使用 jQuery 对 JSON 的内置支持。如果您愿意,可以改用 json.org 库,但getJSON()如果您在解析数据时没有任何异常需求,则相当方便。

于 2009-12-28T18:24:03.077 回答
1

这个问题基本上已经使用另一种方法得到了回答,但是,如果您有兴趣使用该$.ajax方法而不是该$.getJSON方法,您可以这样做:

var rowData;
$.ajax({
    url: "http://tarnfeldweb.com/applewebapps/ajax/recentApps.php",
    type: 'get',
    dataType: 'json' // could also be 'jsonp' if the call is going to another site...
    success: function(data){
        rowData = data; 
    }
});

只是另一种选择,仅此而已...

于 2009-12-28T19:03:28.947 回答
0

您的函数将在成功响应时返回数据。您已经声明了回调函数:

function(data){
    return(JSON.stringify(data));
}

因此,“数据”将包含从请求返回的任何数据,如果您将内容类型声明为 text/json(或 application/json - 我不记得了)并呈现您的 JSON作为响应中的文本,您应该很好。

您可能想要做的是让您的函数将变量声明为 rowData 并从那里开始,所以请执行以下操作:

function(rowData){
    // do something with the rowdata
}

我怀疑你是否需要 stringify 方法,除非你试图将数据写成文本。

于 2009-12-28T18:23:52.407 回答
0

看起来你不明白是如何$.ajax工作的(看起来没人懂)。

$.ajax是一个异步函数,这意味着它不返回任何内容。它只准备一个函数,以便稍后在接收到数据时调用。

您的代码应该看起来更像这样:

var obj = {
 ...
 _rowData: [],
 ...
};

$.getJSON("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", function(data)
{
    // Now data contains your row data, 

    // you can either fill the global object
    obj._rowData = data;
    doSomethingWith(obj);

    // or use data directly
    doSomethingWith({
        ...
        _rowData: data
        ...
    });  
});

// Note that code below will be executed before the AJAX data is received
于 2009-12-28T18:27:38.857 回答