PHP class method called by jQuery
I'm fairly new to jQuery and OOP in PHP, but what I have is a PHP Object that has an array
$array[0] = "a"
$array[1] = "b"
$array[2] = "c"
$array[3] = "d"
and a select box in my HTML
<select class="box">
<option value="1">First Letter</option>
<option value="2">Second Letter</option>
<option value="3">Third Letter</option>
<option value="4">Fourth Letter</option>
</select>
<div></div>
How do I dynamically change whatever is in the div tags as someone changes the value of the select box using jQuery?
Is there a way to do something like
$('.box').change(){ var value = $object->array[index-1]}?
Assuming I had already have t开发者_如何学编程he value for index.
EDIT I know I'll have to use Ajax, but I'm not sure how to call a method in an instance of an object already made.
You can't access PHP through javascript. There are several possible solutions:
- Load all of the possible data combinations at once onto the page stored somewhere in the DOM. As the user cycles through the options, change them appropriately.
- Load only the initial elements onto the page without javascript, then use Ajax to load all other possible combinations.
- Load each combination with ajax on the fly.
You can either have javascript make an Ajax request to the same page and filter the request, or you can create a proxy that will serve only the requests you need when hit with ajax.
Remember that you are trying to combine PHP with Javascript.
Your code will primarily be written in javascript, but you'll only inject bits of PHP code into the javascript code.
As in this instance, use the standard jquery onchange event method 'change()' for the selectbox, set the javascript variable value to $object->array[0] from PHP.
$('select').change(function() {
var value = <?php echo $object->array[$index] ?>
$('div').html(value)
});
You can use the php function json_encode to turn your php data into a javascript object. e.g
<script type="text/javascript">
var mydata = <?= json_encode($myarray) ?>;
console.log(mydata);
</script>
精彩评论