简体   繁体   中英

How to create a JavaScript object from JSON data returned from server

I need help, I want to create a function which returns an object from an AJAX request, so I can create a new object from data on the server like this:

var foo = bar('api.php?x=y');

The function should take a query string as an argument, and the server returns data as JSON.

Can you show me how to do this using jQuery, do you have any ideas/examples?

I will expand on my question because it seems I am doing it all wrong. I am trying to create a web application based on live data (stock quotes) so it has to constantly request updated information from the server. When the app is initialized the first step is getting static data from the stocks to be included (such as ticker symbol and issuer), I am thinking the best way to do this is to have a database on the server and an API which does the query and returns the selected stock data as JSON. The next step is to make a request to another API on the server which returns live data (such as price and volume) on the selected stocks, when the complete data is returned it is rendered to html using a template engine. Then the app has to constantly call the second API on some interval to update the live data and render again. Also you should be able to make a new selection of stocks and start the process again.

I think the best way to structure an app like this is to have the data inside a custom object which has its own methods to modify the data later (for example sorting and filtering), so if foo is my object with the stock data I can do something like foo.sort() , or something like foo.render() to create the html representation of the data. That is why I thought the best way was to create an object from the data returned by the AJAX call. Could you please tell me if this is the right way to structure an app like this or point me in the right direction?

Thanks

AJAX is asynchronous by definition, so it doesn't fit your question particularly well. I would recommend using jQuery.ajax ( see reference ) with a callback instead:

$.ajax({
  url: 'api.php?x=y',
  dataType: 'json',
  success: function (foo) {
    // Do stuff here using 'foo'
  }
});

如果JSON字符串是服务器响应的内容,则只需将它转换为JS对象就很容易了。

var resp_object = JSON.parse(response);

You are thinking synchronously in your approach.

This means that you think that your function call "bar('api.php?x=y')" should immediately return the retrieved data/object. This has the disadvantage that the code execution in the browser is blocked while waiting for the answer.

To overcome this, you would need to create an asynchronous callback handler (the "success" handler when working with "jQuery.ajax" ), as user595228 pointed out before. The code that renders the returned information would go into this handler.

For the question how to structure the code, it depends on how complex the data you get is and how often you use it on your application. If its complex and gets used in several places, it may make sense to create a data object with helper function, to avoid code duplication and put the code regarding your data in one place. If you only render them in one place and the only thing you do is a simple sort and display, i'd go with placing that logic in a simple function, to reduce complexity.

You can create a Jquery plugin and hook your object into. Example:

var foo = tablesort({}); // tablesort is plugin Jquery
foo.sort();

You need implement sort method in Jquery plugin, it mean: get data using ajax from server and fill object's attribute or do something

Is the live data being pushed to you? By that I mean if you don't have something listening at the moment the data goes out over the wire you miss it? Or does it build up in a queue waiting for you to poll it and get it?

If you have the first situation, you can either have your server get the data from the stock service and queue it for you - which brings into question how do you handle the queues for multiple users. Or you can set up either a websocket (HTML5 not supported in all browsers) or take a look at a comet solution (which may involve either a flash object or lots of fast polling).

If you have situation number two, then you can use Ajax to grab the data blocks that are available on a timer. You need to use the asynchronous aspect of ajax or your screen can freeze up waiting on responses. Use something like jquery to help you with that process - no need to reinvent the wheel.

I usually prefer to keep the presentation of the data separate from the data itself. Instead of adding functions to the object after receiving it from the server, I suggest passing the data objects around.

Example:

function renderStockData(data) {
  // build and return HTML from data
}

function loadStockData(url, callback) {
  $.ajax({
    url: url,
    dataType: 'json',
    success: callback
  });
}

// Later that day...
loadStockData('api?stock=GOOG', function (data) {
  var renderedHtml = renderStockData(data);
  // ...
});

Is this the type of advice that you're looking for?

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