문제

A common problem is that for validation you need to run the same code on the server and on the client. On a JavaScript heavy page there are many other function you like to share between both sides. Since you can't run PHP on the client I wounder if it's possible to run a Javascript function from PHP. I am thinking about server-side JS like Rhino but I have no idea how to include it to PHP.

도움이 되었습니까?

해결책

PHP has a V8 extension: http://php.net/manual/en/class.v8js.php never tried it that much, but might be useful

EDIT: here's the pecl package link: http://pecl.php.net/package/v8js

다른 팁

You could use a server side javascript service i.e. node.js and call out to it using PHP, but it would not be a straight forward or trivial solution to the problem. It would probably only be worth it if it was a large application there was an awful lot of crossover in the validation logic.

Try this in php:

echo "<script type='text/javascript'>
         myfunction();
      </script>";

I feel the same as AlexeyKa.

Rather than running JavaScript on both client and server, I think you need to go the opposite route. Create your validation code on the server-side and use Ajax to call the validation before the form submits. That way you are using the same code to validate (no duplications) and you don't have to worry about running a JavaScript engine on your server.

Also, if you give the client the validation code that you will then run on the server, you're just asking for someone to find a hole in your validation code. Keeping validation on the server can keep your validation code away from users.

Update:

I didn't realize your question included more than validation. This isn't a PHP solution, but Google's Closure Tools is a technology that allows your client to be the same as your server. You write UI templates and define how they should work (layout, validation, persistence) and the framework creates the HTML, JavaScript and server code. This is all to ensure that you write code once and any code that is similar between client and server is handled by the framework.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top