클릭으로 PHP 기능 실행
a-tag를 클릭했을 때만 PHP 함수를 호출할 수 있는 간단한 솔루션을 찾고 있습니다.
PHP:
function removeday() { ... }
HTML:
<a href="" onclick="removeday()" class="deletebtn">Delete</a>
업데이트: html 코드와 PHP 코드가 동일한 PHP 파일에 있습니다.
우선, 3개의 언어를 병용하고 있는 것을 이해해 주세요.
PHP: 서버에서만 실행되며 링크 클릭(GET)이나 폼 전송(POST) 등의 요청에 응답합니다.
HTML 및 JavaScript:다른 사용자의 브라우저에서만 실행됩니다(NodeJ 제외).
당신의 파일은 다음과 같이 생겼을 겁니다.
<!DOCTYPE HTML>
<html>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>
PHP는 요청($_REQUEST 경유로 GET, POST, PUT, PATCH, DELETE)에만 응답하기 때문에 같은 파일에 있어도 PHP 기능을 실행해야 합니다.이렇게 하면 "이 사용자를 위해 이 스크립트를 실행해야 합니까?"라는 보안 수준이 제공됩니다.
페이지를 새로 고치지 않으려면 Asynchronous JavaScript and XML(AJAX)이라는 방법을 통해 새로 고치지 않고 PHP에 요청할 수 있습니다.
그건 유튜브에서 찾아볼 수 있는 거지만."jquery ajax"를 검색하면 됩니다.
Laravel을 새로 시작하는 사람에게 추천: http://laravel.com/
javascript에서 ajax 함수를 만듭니다.
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
그럼 html에서 전화하세요.
<a href="" onclick="myAjax()" class="deletebtn">Delete</a>
그리고 당신의 아약스.php에는
if($_POST['action'] == 'call_this') {
// call removeday() here
}
이것은 AJAX를 통해 해야 합니다.jQuery를 사용하여 이 작업을 쉽게 수행할 것을 강력히 권장합니다.
$("#idOfElement").on('click', function(){
$.ajax({
url: 'pathToPhpFile.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
http://api.jquery.com/jQuery.ajax/
버튼이라면 간단한 php로 할 수 있습니다.
<input type="submit" name="submit>
그리고 이것은 당신의 php 코드입니다.
if(isset($_POST["submit"])) { php code here }
전송이 게시되면 코드가 호출되며 버튼을 클릭할 때 코드가 호출됩니다.
페이지 새로고침 없는 솔루션
<?php
function removeday() { echo 'Day removed'; }
if (isset($_GET['remove'])) { return removeday(); }
?>
<!DOCTYPE html><html><title>Days</title><body>
<a href="" onclick="removeday(event)" class="deletebtn">Delete</a>
<script>
async function removeday(e) {
e.preventDefault();
document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
}
</script>
</body></html>
다음은 AJAX의 대체 방법이지만 jQuery는 사용하지 않고 일반 JavaScript만 사용할 수 있습니다.
액션을 호출하고 싶은 첫 번째/메인 php 페이지에 이것을 추가해, 가능성을 변경해 주세요.a
에 (누군가를) 태그 붙이다button
봇이나 악성 앱(또는 기타 모든 것)에 의해 클릭되지 않도록 합니다.
<head>
<script>
// function invoking ajax with pure javascript, no jquery required.
function myFunction(value_myfunction) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML += this.responseText;
// note '+=', adds result to the existing paragraph, remove the '+' to replace.
}
};
xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php $sendingValue = "thevalue"; // value to send to ajax php page. ?>
<!-- using button instead of hyperlink (a) -->
<button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>
<h4>Responses from ajax-php-page.php:</h4>
<p id="results"></p> <!-- the ajax javascript enters returned GET values here -->
</body>
언제?button
를 클릭합니다.onclick
헤드의 Javascript 기능을 사용하여 송신합니다.$sendingValue
다른 php-page에 접속할 수 있습니다.이 예에서는 많은 예를 들 수 있습니다.다른 쪽 페이지에는ajax-php-page.php
는 GET 값을 확인하고 와 함께 반환한다.print_r
:
<?php
$incoming = $_GET['sendValue'];
if( isset( $incoming ) ) {
print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
} else {
print_r("The request didn´t pass correctly through the GET...");
}
?>
응답:print_r
그런 다음 반환되어 다음과 같이 표시됩니다.
document.getElementById("results").innerHTML += this.responseText;
그+=
기존 html 요소를 채우고 추가합니다.+
는 html html 의 및할 뿐입니다.p
소 element"results"
다음과 같은 작업을 수행해 보십시오.
<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
<a href="#" onclick="doSomething();">Click Me!</a>
이것이 가장 쉬운 방법입니다.양식이 투고되면 php 기능을 수행합니다.(페이지를 새로고침할 필요 없이) 비동기적으로 기능을 수행하려면 AJAX가 필요합니다.
<form method="post">
<button name="test">test</button>
</form>
<?php
if(isset($_POST['test'])){
//do php stuff
}
?>
이거 한번 해봐, 잘 될 거야.이것은 폼 태그와 버튼 태그 없이 동작합니다.
<div onclick="window.location='?hello=true';">
<?php
if(isset($_GET['hello'])) {
hello();
}
function hello()
{
echo "hello world";
}
?>
언급URL : https://stackoverflow.com/questions/19323010/execute-php-function-with-onclick
'itsource' 카테고리의 다른 글
스캐너 클래스에서 next() 메서드와 nextLine() 메서드의 차이점은 무엇입니까? (0) | 2022.09.12 |
---|---|
C#에 null margeing 연산자(--)와 동등한 Java가 있습니까? (0) | 2022.09.12 |
RxJs Subject 또는 Observable의 현재 값을 얻는 방법 (0) | 2022.09.12 |
MySQL/PHP를 사용하여 필드에 now()를 사용하여 현재 날짜/시간을 삽입합니다. (0) | 2022.09.12 |
셀 값을 날짜로 설정하고 기본 Excel 날짜 형식을 적용하려면 어떻게 해야 합니까? (0) | 2022.09.12 |