javascriptjquerystringjsondashcode

How might I populate an object property using a JSON-encoded server response?


How can i turn this:

<? echo json_encode($myArrays); ?>

...into this:

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

My script returns that ^, but i dont know how to put the data into the string, _rowData ? P.S. I am using Dashcode, trying to dynamically load items into a List Controller

So far, i have this:

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

rowData: recentListControllerXHR,

Solution

  • Ok - your problem appears to be a misunderstanding of how asynchronous APIs work. $.ajax() makes a request, and at some point in the future calls the provided callback with the response.

    Assuming you have a name for the object you're populating, you can fill in the desired property using something like this:

    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.
      });
    

    Note that I'm using jQuery's built-in support for JSON here. You can use the json.org library instead if you wish, but getJSON() is rather convenient if you don't have any unusual needs when parsing the data.