“转换" PHP到Javascript [英] "Convert" PHP to Javascript
问题描述
我正在使用CodeIgniter,并且在模型中有一个PHP MySQL语句:
I'm using CodeIgniter and I have a PHP MySQL Statement in a model:
function getAllDevices() {
$query = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer");
return $query->result();
}
然后我将其通过控制器传递给我的视图,
I then pass this through my controller to my view using:
$this->load->model("get_device");
$data['results'] = $this->get_device->getAllDevices();
并使用以下PHP将其输出到div中:
And output this into a div using the following PHP:
<div class="hold-cont">
<div class="holder">
<div class="image-hold"><img class="image-icon" src="<?php echo base_url(); ?>assets/images/devices/<?php echo $row->Image; ?>"></div>
</div>
<div class="device-name devicename-txt">
<?php $mod = $row->Model;
$model = str_replace(" ","-",$mod);
?><a href="<?php echo base_url(); ?>roms?device=<?php echo($row->Manufacturer . '-' . $model); ?>"><?php echo($row->Manufacturer. ' ' .$row->Model); ?></a><br>
</div>
</div><?php } ?>
这目前可以正常工作,但是我现在在页面中合并了一个搜索框,该搜索框使用jQuery函数自动完成功能,并使用$ results的JSON数组
This currently works fine, however I have now incorporated a searchbox into my page which uses the jQuery function autocomplete and uses the JSON Array of $results
我需要做的是将PHP转换"为Javascript,这将使页面可以使用JSON数组进行填充.然后,我需要能够使用它来将选择从搜索框中传递到查询中,这将更改页面上的内容而无需重新加载.
What I need to do is "convert" the PHP into Javascript which will enable the page to be populated using the JSON Array. I then need to be able to use this to pass the selection from the search box into a query which will change the content on the page without reloading it.
我该如何处理?之前,我使用jQuery中的ajax函数将方法混合在一起,但是这需要一个URL,其中包含一个PHP MySql语句,而我现在无法执行该语句.这样做的想法是,使其在页面加载时仅运行1个SQL查询,而我无法更改此方法.
How can I go about this? I previously mashed together a way of doing it using the ajax function in jQuery, however this requires a URL which contained a PHP MySql statement which I cannot do now. The idea behind doing it like this is so it only runs 1 SQL Query when the page loads and I cannot change this method.
推荐答案
没有什么可以阻止PHP编写" JavaScript.
There is nothing to stop PHP "writing" Javascript.
您需要手动或通过使用PHP的json_encode
方法(实际上将一个PHP对象转换为JSON表示法)来构建一个格式正确的Javascript对象.假设您的PHP对象位于$row
中,则类似于:
You would need to build up a suitably formatted Javascript object either manually or by using the json_encode
method of PHP (which essentially turns a PHP object into it's JSON notation). Assuming your PHP object is in $row
then something like:
<code>
<script language="text/javascript">
var jsObject = <?php json_encode($row); ?>
</script>
</code>
将在jsObject中给您一个Javascript对象,其中包含与PHP $ row对象的属性相对应的键和值,然后您就可以从Javascript中使用该对象.
Would give you a Javascript object in jsObject containing keys and values corresponding to the properties of the PHP $row object that you can then work with from Javascript.
这篇关于“转换" PHP到Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!