Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

"Convert" PHP to Javascript

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();

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 } ?>

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is nothing to stop PHP "writing" Javascript.

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>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...