【问题标题】:I want to seperate the PHP JSON string in jQuery [closed]我想在 jQuery 中分离 PHP JSON 字符串 [关闭]
【发布时间】:2015-11-02 08:26:56
【问题描述】:

我在分离 json 数组结果时遇到问题。当我在 jquery 中提醒 json 结果时,它会返回以下数组。

{"productid":"17","product_quantity":"2"}{"productid":"9","product_quantity":"1"}

现在我想将不同变量中的每个值分开。

提前谢谢。

【问题讨论】:

  • 那不是有效的 json。
  • 我重新格式化以通过 json 有效性测试 here
  • 这个问题完全没有意义。您应该解释不同变量中每个值的含义?

标签: javascript php jquery arrays json


【解决方案1】:

这不是一个有效的 json 字符串。 首先,您可以将输入转换为 json 字符串。 然后,您可以使用 JSON.parse 来获取 js 数组。

例如

首先你需要这样做:

input = '[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]'

然后:

input_array = JSON.parse(input)

【讨论】:

    【解决方案2】:

    可能是您的服务器返回的字符串不是有效的 JSON。一个有效的例子是:

    [{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]
    

    你是如何创建 json 的?由于您标记了 PHP,正确的方法(如果您有一个数组)是这样的,它将返回您 JS 可以处理的有效 JSON:

    echo json_encode($array);
    

    【讨论】:

      【解决方案3】:

      您提供的 json 格式错误。我认为这是一个错字。

      使用 JSON.parse 转换为 javascript 对象。

      var jsonString = [{"productid":"17","product_quantity":"2"}, {"productid":"9","product_quantity":"1"}];
      var data = JSON.parse(jsonString);
      console.log(data[1].productid);  // 9
      

      但我不知道你的意思。“现在我想将不同变量中的每个值分开。”

      为什么? 无论如何,你可以做到这一点。虽然我确实说不要。但你问了。

      data.forEach(function(item){
          window["productid"+item.productid] = item.product_quantity;
      });
      

      将在全局范围内为您提供 2 个变量

      console.log(productid17); // "2"
      console.log(productid9); // "1"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多