简体   繁体   English

为什么ajax请求中的JSON或为什么不

[英]Why JSON in ajax request or why not

I want to know when will it be reasonable to pull data from a php page via ajax in form of json array.. Suppose I have this code : 我想知道何时通过ajax以json数组的形式从php页面中提取数据是合理的。假设我有这样的代码:

$.ajax({
    type: "get",
    url: "assets/update_cart_user_fstore.php",
    data: up,
    cache: false,
    success: function(r){
            $(#item).html(r);
    },
});

and in PHP page I am echoing a variable 在PHP页面我回应一个变量

$hello = "I am code!";
echo $hello;

And with JSON 并使用JSON

$.ajax({
    type: "get",
    url: "assets/update_cart_user_fstore.php",
    data: up,
    cache: false,
    success: function(r){
        var obj = jQuery.parseJSON(r);
        $('#item').html(obj.code);
    },
});

and in PHP I'm echoing the JSON array 在PHP中,我正在回应JSON数组

$hello = "I am code!";
$response = array();
$response['code'] = $hello;
echo json_encode($response);

Now I know that in case of echoing more than 1 variable JSON is appropriate...But is it necessary here? 现在我知道,如果回显多于1个变量JSON是合适的......但是这里有必要吗? And am I using JSON properly..? 我正在使用JSON吗?

Please explain.. 请解释..

Is it necessary in this case? 在这种情况下是否有必要 No, it isn't. 不,不是。

But using JSON has some advantages, for example 但是,例如,使用JSON有一些优点

  • Your data has a strict, standardized structure. 您的数据具有严格的标准化结构。 This means, less chance for errors. 这意味着错误的可能性更小。
  • You can scale it better. 你可以更好地扩展它。
  • You can debug it easier. 您可以更轻松地调试它。 For example, Tools like Firebug support JSON 例如,像Firebug这样的工具支持JSON

Two good articles, which will go into more detail: 两篇好文章,将详细介绍:

  1. http://www.revillweb.com/articles/why-use-json/ http://www.revillweb.com/articles/why-use-json/
  2. http://blog.programmableweb.com/2013/11/07/xml-vs-json-a-primer/ http://blog.programmableweb.com/2013/11/07/xml-vs-json-a-primer/

I've rarely found a use case where I wouldn't prefer JSON. 我很少发现一个我不喜欢JSON的用例。

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

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