JavaScript에서 PHP 함수 호출
JS 함수를 통해 PHP 함수를 실행할 수있는 방법이 있습니까?
이 같은:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
기본적으로 PHP 함수를 query("hello")
호출하는 "Test"라는 href를 클릭 하면 php 함수를 실행하고 싶습니다 .
이것은 무엇을, 본질에서, AJAX가 있다 위해 . 페이지가로드되고 요소에 이벤트를 추가합니다. 사용자가 무언가를 클릭하여 이벤트가 트리거되도록하면 Javascript는 XMLHttpRequest 객체 를 사용하여 서버에 요청을 보냅니다.
서버가 (아마도 출력으로) 응답 한 후, 다른 자바 스크립트 함수 / 이벤트는 다른 HTML과 마찬가지로 페이지에 단순히 붙이는 것을 포함하여 해당 출력으로 작업 할 수있는 장소를 제공합니다.
일반 자바 스크립트를 사용하여 "손으로"할 수도 있고 jQuery를 사용할 수도 있습니다. 프로젝트의 크기와 특정 상황에 따라 일반 자바 스크립트를 사용하는 것이 더 간단 할 수 있습니다.
일반 자바 스크립트
이 매우 기본적인 예에서는 myAjax.php
사용자가 링크를 클릭 할 때로 요청을 보냅니다 . 서버는 일부 콘텐츠,이 경우 "hello world!"를 생성합니다. 우리는 id로 HTML 요소에 넣을 것 output
입니다.
자바 스크립트
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
시도해보세요 : http://jsfiddle.net/GRMule/m8CTk/
자바 스크립트 라이브러리 사용 (jQuery 외)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
var function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
- AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest
on MDN - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx- jQuery - http://jquery.com/download/
jQuery.ajax
- http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
참고URL : https://stackoverflow.com/questions/7165395/call-php-function-from-javascript
'code' 카테고리의 다른 글
SQL Server에서 쿼리 시간 제한 강제 (0) | 2020.10.16 |
---|---|
Android SeekBar 최소값 (0) | 2020.10.16 |
SVG 문서는 사용자 정의 데이터 속성을 지원합니까? (0) | 2020.10.16 |
SQL Server 연결 문자열을 설정하는 방법은 무엇입니까? (0) | 2020.10.16 |
HTML5 캔버스에서 흐릿한 텍스트를 수정하려면 어떻게해야합니까? (0) | 2020.10.16 |