PHP에서 JavaScript 함수를 호출하는 방법?
PHP에서 JavaScript 함수를 호출하는 방법?
<?php
jsfunction();
// or
echo(jsfunction());
// or
// Anything else?
다음 코드는 xyz.html (버튼 클릭시) wait()
에서 외부 xyz.js 에서 a 를 호출합니다 . 이것은 wait()
wait.php를 호출합니다.
function wait()
{
xmlhttp=GetXmlHttpObject();
var url="wait.php"; \
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
if(xmlhttp.readyState==4) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
그리고 wait.php
<?php echo "<script> loadxml(); </script>";
여기서 loadxml()
같은 방법으로 다른 PHP 파일의 코드를 호출합니다.
는 loadxml()
달리 잘 작동되지만 내가 원하는 방식으로 호출되지 않습니다.
PHP에 관한 한 (또는 실제로는 웹 서버) HTML 페이지는 큰 문자열보다 복잡하지 않습니다.
데이터베이스와 웹 서비스에서 읽는 PHP와 같은 언어로 할 수있는 모든 멋진 작업-궁극적 인 최종 목표는 정확히 동일한 기본 원칙입니다 : HTML * 문자열 생성.
큰 HTML 문자열은 웹 브라우저에 의해로드 될 때까지 그보다 특별한 것이 아닙니다. 브라우저 페이지가로드되면 다음 레이아웃, 박스 모델 물건, DOM 생성 및 자바 스크립트 실행을 포함한 다른 많은 것들 - 다른 모든 마법이 발생합니다.
따라서 "PHP에서 JavaScript를 호출"하지 말고 "출력에 JavaScript 함수 호출을 포함"하십시오.
이를 수행하는 방법에는 여러 가지가 있지만 여기에 몇 가지가 있습니다.
PHP 만 사용 :
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
PHP 모드에서 직접 출력 모드로 탈출 :
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
함수 이름이나 그와 비슷한 것을 반환 할 필요가 없습니다. 우선, AJAX 요청을 직접 작성하지 마십시오. 당신은 자신을 힘들게 만들고 있습니다. jQuery 또는 다른 우수한 프레임 워크 중 하나를 얻으십시오.
둘째, AJAX 호출에서 응답을 받으면 이미 JavaScript 코드를 실행 중임을 이해하십시오.
다음은 jQuery의 AJAX로 수행하고 있다고 생각하는 예입니다.
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
이제 함수 이름을 PHP에서 AJAX 호출로 다시 보내야하는 경우에도 그렇게 할 수 있습니다.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* 또는 JSON 또는 XML 등
나는 항상 그냥 echo "<script> function(); </script>";
비슷한 것을 사용 합니다. PHP에서 기술적으로 함수를 호출하지는 않지만 얻을 수있는 한 가깝습니다.
현재 (2012 년 2 월)이를위한 새로운 기능이 있습니다. 여기를 확인 하십시오
코드 샘플 (웹에서 가져옴) :
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
당신은 할 수 없습니다. PHP가 출력 한 HTML에서 JS 함수를 호출 할 수 있지만, 그것은 완전히 다른 것입니다.
나중에 실행하기 위해 반향을 일으키려면 괜찮습니다.
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference: What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).
<td onClick= loadxml()><i>Click for Details</i></td>
function loadxml()
{
result = loadScriptWithAjax("/script.php?event=button_clicked");
alert(result);
}
// script.php
<?php
if($_GET['event'] == 'button_clicked')
echo "\"You clicked a button\"";
?>
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
try like this
<?php
if(your condition){
echo "<script> window.onload = function() {
yourJavascriptFunction(param1, param2);
}; </script>";
?>
You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:
<button onclick="xajax_addCity();">Add New City</button>
Our intuitive guess would be that xajax_addCity()
is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity()
, but what we do have is a PHP function called addCity()
that can do whatever PHP does!
<?php function addCity() { echo "Wow!"; } ?>
Think about it for a minute. We are virtually invoking a PHP function from Javascript code! That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!
if you want to call method inside echo you have to enclose them into single quotes:
function f() {
//code
alert("its calling from echo ");
}
echo "<td onclick='f();'>".Method calling."</td>";
참고URL : https://stackoverflow.com/questions/1045845/how-to-call-a-javascript-function-from-php
'IT' 카테고리의 다른 글
JQuery를 사용하여 HTML 5 비디오 재생 / 일시 정지 (0) | 2020.05.12 |
---|---|
각도 2 @ViewChild 주석은 정의되지 않은 값을 반환합니다. (0) | 2020.05.12 |
현재 경로 이름을 얻는 방법? (0) | 2020.05.12 |
Visual Studio 2010은 항상 프로젝트가 오래되었다고 생각하지만 아무것도 변경되지 않았습니다. (0) | 2020.05.12 |
C #에서 추상 클래스의 생성자 (0) | 2020.05.12 |