doukun1450 2011-10-19 08:34
浏览 49
已采纳

从AJAX调用操作数据:PHP还是Javascript?

This is a general question. Using an example below, suppose that I have a Javascript that performs an AJAX call on a PHP script to pull data from a database. I can choose to:

a) manipulate the data on the PHP script itself before encoding an sending it back to the Javascript, OR;

<?php
 while ($row = mysqli_fetch_assoc($result))
 {
  extract($row);
  array_push($data, array('product' => $product, 'discount' => $price*0.15));
 }
 echo json_encode($data);
?>

b) get raw data from the PHP script and do the manipulation on the Javascript.

<SCRIPT type='text/javascript'>
 $.each(json, function(index, element) {
  element.discount = 0.15*element.price
 }
</SCRIPT>

Though I already know that I can get better performance (server-side) using option b), I would like to hear from the community whether it is a wiser choice and whether there are any logical arguments against it which I may have overlooked. Thanks!

NOTE:

  • This is just a simple scenario, the calculations are more complicated than *0.15.
  • Javascript is a must-have to pull data and for application to work.
  • 写回答

3条回答 默认 最新

  • dongmei8511 2011-10-19 08:42
    关注

    Some things you do not want to be stingy on when it comes to performance or time taken to execute.

    • Cryptography is one of them.
    • Anything with a financial aspect to it, is another.

    The fact that we can do XYZ on the client layer, through JavaScript doesn't mean that we should be compelled to do it. What happens

    A) If JavaScript is turned off. B) You rely on the value POSTed from JavaScript. (Imagine a shopping cart which has $_POST['total_amount'] which is used by the server. I am going to edit that POST or hidden input to get free things.

    If what you are doing is purely informative, then this does not matter as much, but if you rely on any information, then you should be checking the prices multiple times.

    Additionally, what happens when you want to start providing an API or something to your service. Your transport is now broken because it doesn't contain the calculated prices.

    DO it server side, at whichever layer better. As Duncan says, SQL could be one option, or PHP. I don't have a preference on this one since any gains for a smallset of items will be largely negligible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题