I have been looking at this problem for quite a while now and cannot seem to figure out why I keep receiving null after my $.ajax function is called.I input an associative array that contains my method name and then call my method in PHP to return aj son string back to the front end. I receive null when I call alert in my java script. Here is my code
Java script:
$(document).ready(function()
{
var data = {};
data["Method"] = "test";
$.ajax({
url:"test.php/test",
data: data,
type:"POST",
contentType:"application/json",
dataType:"json",
success: function(data){
alert(data);
},
error:function(data, textStatus, error)
{
}
});
});
PHP:
<?
//require_once("database.php");
class methods
{
function __contructor()
{
if(isset($_POST["Method"]))
{
$function = $_POST["Method"];
call_user_func($function);
}
else
{
echo "{\"status\":\"false\"}";
}
}
function test()
{
$json = array(
"kyle" => "broflowksi",
"eric" => "cartman",
"stan" => "marsh"
);
echo json_encode($json);
}
}
$method = new methods();
?>
What you are trying to call is an instance method. Call it this way:
if(isset($_POST["Method"]))
{
$function = $_POST["Method"];
$method = new ReflectionMethod('methods', $function);
$method->invoke($this);
}
在发送输出之前尝试强制使用内容类型标头,
header("Content-type: application/json");
There's simply a typo in your class constructor method, it should be
function __construct()
One other thing to keep in mind is that I'm not sure you should be setting the contentType to json, as that variable is for what you're sending... not what you're receiving. So if you end up having a situation where the post variables are being stripped, try and remove the contentType form your ajax call.
Try removing the echo
in test
method. You are calling
call_user_func($function);
and your $function
is not returning
but echoing
, .ie
function test() {
$json = array(
"kyle" => "broflowksi",
"eric" => "cartman",
"stan" => "marsh"
);
echo json_encode($json); // This line should be returning
}
I had dealt with similar issue earlier with a php function call (not in ajax particular).to catch.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.