简体   繁体   English

如何从服务器返回的JSON数据创建JavaScript对象

[英]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: 我需要帮助,我想创建一个从AJAX请求返回对象的函数,因此可以从服务器上的数据创建一个新对象,如下所示:

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

The function should take a query string as an argument, and the server returns data as JSON. 该函数应将查询字符串作为参数,服务器将数据作为JSON返回。

Can you show me how to do this using jQuery, do you have any ideas/examples? 您能告诉我如何使用jQuery进行操作吗?您有任何想法/示例吗?

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. 我试图基于实时数据 (股票报价)创建一个Web应用程序,因此它必须不断地从服务器请求更新的信息。 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. 初始化应用程序时,第一步是从要包含的股票中获取静态数据(例如股票代号和发行人),我认为做到这一点的最佳方法是在服务器上拥有一个数据库,并使用一个API查询并将选定的库存数据作为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. 下一步是向服务器上的另一个API发出请求,该API返回所选股票的实时数据(例如价格和数量),当返回完整数据时,将使用模板引擎将其呈现为html。 Then the app has to constantly call the second API on some interval to update the live data and render again. 然后,该应用程序必须在某个时间间隔内不断调用第二个API,以更新实时数据并再次呈现。 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. 我认为构建这样的应用程序的最佳方法是将数据保存在自定义对象中,该对象具有自己的稍后修改数据的方法(例如排序和过滤),因此,如果foo是我的股票数据对象,则可以执行类似foo.sort()或类似foo.render()来创建数据的html表示形式。 That is why I thought the best way was to create an object from the data returned by the AJAX call. 这就是为什么我认为最好的方法是根据AJAX调用返回的数据创建对象。 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. 根据定义,AJAX是异步的,因此它不太适合您的问题。 I would recommend using jQuery.ajax ( see reference ) with a callback instead: 我建议将jQuery.ajax( 请参阅参考资料 )与回调一起使用:

$.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. 这意味着您认为函数调用“ bar('api.php?x = y')”应立即返回检索到的数据/对象。 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. 为了克服这个问题,您需要创建一个异步回调处理程序(使用“ jQuery.ajax”时为“成功”处理程序),如user595228之前指出的那样。 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. 您可以创建一个Jquery插件并将对象挂接到其中。 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 您需要在Jquery插件中实现sort方法,这意味着:使用ajax从服务器获取数据并填充对象的属性或执行某些操作

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). 或者,您可以设置一个websocket(并非所有浏览器都支持HTML5)或查看一个彗星解决方案(可能涉及Flash对象或大量快速轮询)。

If you have situation number two, then you can use Ajax to grab the data blocks that are available on a timer. 如果遇到第二种情况,则可以使用Ajax来获取计时器上可用的数据块。 You need to use the asynchronous aspect of ajax or your screen can freeze up waiting on responses. 您需要使用ajax的异步方面,否则屏幕可能会冻结等待响应。 Use something like jquery to help you with that process - no need to reinvent the wheel. 使用类似jquery的东西可以帮助您完成该过程-无需重新发明轮子。

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? 这是您正在寻找的建议类型吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM