使用jQuery / javascript仅筛选出我需要的列的JSON

时间:2021-04-19 10:20:02

I'm using this to parse out the JSON coming from PHP (age_get.php) and it's working great.

我正在使用它来解析来自PHP的JSON(age_get.php)并且它工作得很好。

$.getJSON('age_get.php', function(data) {
  var ticks1=[]
  $.each(data, function(key, val) {                  
  ticks1.push("["+val.index+",'"+val.value+"']");
            });
var ticks6 =[(ticks1.join())]

The output is this, which as I said is fine.

输出就是这个,正如我所说的那样好。

["[90,'18-24'],[91,'25-29'],[92,'30-34'],[93,'35-39'…'60-64'],[99,'65-69'],[100,'70-74'],[101,'75-99']"]

In my PHP file, the mySQL query part is this:

在我的PHP文件中,mySQL查询部分是这样的:

$sql = "select * from advanced_data where category like 'age range'";

So, basically, I have the PHP already "filtering" the JSON from a much larger table (i.e., with many more columns).

所以,基本上,我已经让PHP从一个更大的表中“过滤”了JSON(即,有更多的列)。

There has to be a better way than creating individual PHP files for each time I need something out of this database, but I'm pretty new to this.

每次我需要这个数据库的东西时,必须有一个比创建单个PHP文件更好的方法,但我对此很新。

So, the question is, can I have a single PHP file with a query more like this:

所以,问题是,我可以使用一个带有查询的单个PHP文件,如下所示:

$sql = "select * from advanced_data;

And then in my HTML file/jQuery have something that essentially filters out the JSON for what I need similar to how "where category like 'age range'" works in my PHP file.

然后在我的HTML文件/ jQuery中有一些东西基本上过滤掉了我需要的JSON,类似于“我的PHP文件中的'age range'这样的类别”。

Hope that's clear. Any thoughts would be appreciated.

希望很清楚。任何想法将不胜感激。

1 个解决方案

#1


1  

Yes you can do that technically, but it is not a good idea. When using ajax, it is good to keep the data small.

是的,你可以在技术上做到这一点,但这不是一个好主意。使用ajax时,最好保持较小的数据。

Instead of get everything from php and search it with js loop, you can improve your php script to let it accept queries.

而不是从PHP获取所有内容并使用js循环搜索它,您可以改进您的PHP脚本,让它接受查询。

In your php:

在你的PHP中:

<?php 
$whereCategory = isset($_GET['category'])? "where category like '{$_GET['category']}'" : '';
$sql = "select * from advanced_data {$whereCategory};";
...

In your ajax:

在你的ajax中:

$.getJSON('age_get.php?category=testCategory', function(data) {
  ...
});

#1


1  

Yes you can do that technically, but it is not a good idea. When using ajax, it is good to keep the data small.

是的,你可以在技术上做到这一点,但这不是一个好主意。使用ajax时,最好保持较小的数据。

Instead of get everything from php and search it with js loop, you can improve your php script to let it accept queries.

而不是从PHP获取所有内容并使用js循环搜索它,您可以改进您的PHP脚本,让它接受查询。

In your php:

在你的PHP中:

<?php 
$whereCategory = isset($_GET['category'])? "where category like '{$_GET['category']}'" : '';
$sql = "select * from advanced_data {$whereCategory};";
...

In your ajax:

在你的ajax中:

$.getJSON('age_get.php?category=testCategory', function(data) {
  ...
});