我熟悉如何使ajax调用php页面并执行一系列操作,然后返回json数据。但是是否可以调用给定页面中的特定函数?
基本上,我想要减少项目中文件的数量。因此,我可以将许多常用函数放在一个页面中,然后只调用我需要的函数。
我熟悉如何使ajax调用php页面并执行一系列操作,然后返回json数据。但是是否可以调用给定页面中的特定函数?
基本上,我想要减少项目中文件的数量。因此,我可以将许多常用函数放在一个页面中,然后只调用我需要的函数。
对于 AJAX 请求
在你的网页中引入 jQuery 库。例如:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
点击按钮时调用一个函数
<button type="button" onclick="create()">Click Me</button>
点击按钮时,在JavaScript中调用create函数。
<script>
function create () {
$.ajax({
url:"test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc@gmail.com"},
success:function(result){
console.log(result.abc);
}
});
}
</script>
在服务器端的test.php文件中,应该读取动作POST参数,并对应值执行PHP动作,并以JSON格式返回,例如:
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
您不能直接从AJAX请求调用PHP函数,但可以使用以下方法:
<? php
function test($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo test($_POST['callFunc1']);
}
?>
<script>
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { console.log(response); }
});
</script>
作为这种目的的结构,我建议使用以下内容:
<?php
if(isset($_POST['action'])){
if ($_POST['action'] == "function1") { func1(); }
if ($_POST['action'] == "function2") { func2(); }
if ($_POST['action'] == "function3") { func3(); }
if ($_POST['action'] == "function4") { func4(); }
}
function func1(){
//Do something here
echo 'test';
}
?>
var data = { action: 'function1' };
$.post(ajaxUrl, data, function(response) {
if(response != "") {
$('#SomeElement').html(response);
}else{
alert('Error, Please try again.');
}
});
如果我理解正确的话,是的,你可以这样做。 将所有函数放在一个PHP文件中,并使用ajax作为参数传递要调用哪个函数。然后使用switch或if结构,执行你想要的函数。
jQuery:
$(document).ready(function(){
$('#tfa_1117700').change(function(){
var inputValue = $(this).val();
var v_token = "{{csrf_token()}}";
$.post(
"{{url('/each-child')}}",
{ dropdownValue: inputValue,_token:v_token },
function(data){
console.log(data);
$('#each-child-html').html(data);
}
);
});
});
PHP:
public function EachChild(Request $request)
{
$html ="";
for ($i=1; $i <= $request->dropdownValue; $i++)
{
$html = $i;
}
echo $html;
}