如何将JavaScript和PHP应用于按钮?
单击按钮时:如何将JavaScript和PHP应用于按钮?,javascript,php,Javascript,Php,单击按钮时: 我需要JavaScript来执行一些功能 还可以运行PHP代码 我们如何才能做到这一点?PHP只由服务器运行,并响应诸如单击链接/按钮(GET)或提交表单(POST)之类的请求 HTML和JavaScript仅在某人的浏览器中运行 <html> <?php function PhpFunction() { echo 'A php function'; } if (isset($_GET['JsFunction'])) { PhpFun
我们如何才能做到这一点?PHP只由服务器运行,并响应诸如单击链接/按钮(GET)或提交表单(POST)之类的请求 HTML和JavaScript仅在某人的浏览器中运行
<html>
<?php
function PhpFunction() {
echo 'A php function';
}
if (isset($_GET['JsFunction'])) {
PhpFunction();
}
?>
Hello there!
<a href='index.php?JsFunction=true'>Run PHP Function On Click Of This Link</a>
</html>
你好!
或者,
您可以创建一个ajax请求以在服务器中运行php代码。ajax可以帮助您向php(或其他)可以捕获的服务器发送一个异步请求,通过这种方式,您可以实现并使用一些回调函数
$.ajax({
url : "yourScript.php", // the resource where youre request will go throw
type : "POST", // HTTP verb
data : { action: 'myActionToGetHits', param2 : myVar2 },
dataType: "json",
success : function (response) {
//in your case, you should return from the php method some fomated data that you //need throw the data var object in param
data = toJson(response) // optional
//heres your code
},
error : //some code,
complete : //...
});
在php脚本中,您将收到POST请求,并抛出类似POST的超全局变量(例如本例)
让javascript进行提交:
function button1() {
// js code here
var formelt = document.getElementById("form1");
formelt.submit(); // this will submit the form to server
}
示例=>
<button class="btn-test">Btn Test</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
jQuery('.btn-test').click(function() {
js_do_something();
php_do_something();
});
function js_do_something() {
console.log('something done from js');
}
function php_do_something() {
console.log('something done from php');
jQuery.ajax({
type: "POST",
url: 'you_php_file.php',
data: {param: 'btn-test-click'},
success: function () {
console.log('success');
}
});
}
</script>
Btn测试
jQuery('.btn test')。单击(函数(){
做某事;
php_do_something();
});
函数js_do_something(){
log(“从js完成的事情”);
}
函数php_do_something(){
log('somethindoefromphp');
jQuery.ajax({
类型:“POST”,
url:“you_php_file.php”,
数据:{param:'btn test click'},
成功:函数(){
console.log('success');
}
});
}
这里介绍了如何使用Onclick执行php函数
假设您使用jQuery,则可以执行Javascript函数,如下所示:
jQuery('#id-button').on('click', function(){
// your function body
});
多个选项,尝试了什么吗?可能是重复的谢谢你的解释。但是有没有一种方法可以同时运行javascript和php呢。
<button class="btn-test">Btn Test</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
jQuery('.btn-test').click(function() {
js_do_something();
php_do_something();
});
function js_do_something() {
console.log('something done from js');
}
function php_do_something() {
console.log('something done from php');
jQuery.ajax({
type: "POST",
url: 'you_php_file.php',
data: {param: 'btn-test-click'},
success: function () {
console.log('success');
}
});
}
</script>
jQuery('#id-button').on('click', function(){
// your function body
});