开发者

Running PHP inside of a Javascript loop, any way to keep track of iterations?

开发者 https://www.devze.com 2023-02-22 16:03 出处:网络
I was wondering if there was any possible way to keep track of JavaScript variables within a for loop inside PHP.

I was wondering if there was any possible way to keep track of JavaScript variables within a for loop inside PHP.

I definitely know that this is not good design. However, I'm trying to hack some existing code. If I am able to make this work, I may not have to dump the existing code...

Thanks you guys. Any hacks, tips, tricks will work!!

Example:

//JavaScript for loop
for (var i = 0; i <4; ++i) {

    //Echo the JavaScript variable "i", the iteration of the loop
    <?php echo /*JavaScript var i */ ;   ?>

}

EDIT: More background info

I'm working on a project where the data is supplied through XML and the API is written in PHP and returns an PHP array. The front end is designed whilst using a lot of JavaScript. I'm going to need to populate JavaScript fields with fields from my PHP object through multiple iterations. Hence, the PHP inside the JavaScript for loop.

Neither t开发者_高级运维he front end nor the back end is written by me, mind you. :P


You fundamentally misunderstand how PHP and Javascript work. PHP is executed on the server, while the page is being generated, BEFORE the page is sent to the client.

Javascript kicks in afterwards, after the page has been generated and received by the client.

What you're trying to do is getting a driver to change the radio station in a car while the car's still on the assembly line in the factory. Not possible.


That will definitely not work.

The JavaScript loop's body will be whatever PHP echoes, and in your example, that is not valid PHP syntax.

Example

Imagine this is a HTML view...

for (var i = 0; i < 4; ++i) {
    <?php echo 'a';   ?>
}

...the output would be...

for (var i = 0; i < 4; ++i) {
    a
}


You cant mix server side scripting and client side scripting.

For this purpose only AJAX is made. :)

You can go with jquery, mootool, closure... etc


I think I understand what you are trying to do. If on a basic level, you want to use the value from a PHP variable within the javascript on your client side, they you need to echo out a whole section and 'print' the php value and assign it to a javascript variable.

This post talks about it: http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/290401

If I'm on the wrong track, then have a read anyway :)

0

精彩评论

暂无评论...
验证码 换一张
取 消