[英]Calling method in PHP file from separate JavaScript file
I have a javascript file from which I am trying to make a ajax call to execute method of a different php file. 我有一个javascript文件,试图从该javascript文件进行ajax调用以执行其他php文件的方法。
Javascript file - a.js Javascript文件-a.js
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {"updateMethod()"}
success:function(result){
console.log(result);
}
});
}
PHP file - abcd.php PHP文件-abcd.php
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
I am not able to make a call to the PHP method. 我无法调用PHP方法。 What is wrong with my AJAX query or what do I need to do in PHP file side to call the method. 我的AJAX查询出了什么问题,或者我需要在PHP文件端做些什么来调用该方法。
I don't know what you try to do, but you can do it this way: 我不知道您要尝试做什么,但是您可以这样进行:
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {methodName: "updateMethod"},
success:function(result){
console.log(result);
}
});
}
On server side: 在服务器端:
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();
Remove this line 删除此行
dataType: 'json',
and send data without json 并发送没有json的数据
If you sending json in php must be: 如果您在php中发送json必须是:
$data = file_get_contents('php://input');
PHP "php://input" vs $_POST PHP“ php:// input”与$ _POST
Or beter jquery: 或者更好的jQuery:
var methodName = "YourMethodName";
var y = "Cymbal";
$.post( "test.php", { methodName: methodName, lastname: y })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Maybe something like this is more secure and I think you also need function arguments for CRUD actions(Not tested): 也许像这样更安全,我认为您还需要CRUD操作的函数参数(未经测试):
backend: 后端:
class CRUD
{
public function update($args)
{
$input = $args['exampleInput'];
// sanitize input
// prepared query
// $stmt->execute($input);
}
}
function access($class, $method, $args)
{
if (method_exists($class, $method)) {
return call_user_func_array([$class, $method], [$args]);
}
}
$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));
js: JS:
function handleAction(methodName, arguments) {
$.ajax({
url: "crudFile.php";
type: "POST",
data: { method: methodName, args: arguments },
dataType: 'json',
success: function (result) {
console.log(result);
}
});
}
var inputs = {
exampleInput: function () {
return document.getElementById('your-div-id').textContent();
},
};
// usage
handleAction('update', inputs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.