I'm using this simple PHP
framework, after some upsets with others Custom PHP
I have the following controller:
<?php
class TestController extends BaseController
{
public function __construct($action, $urlValues) {
parent::__construct($action, $urlValues);
}
public function deploy_test() {
echo json_encode("helloworld");
}
}
?>
That function is activated by a .js
function called test()
:
function test()
{
var data = {
config : $("#config").val(),
machines : $("#machines").val(),
test : $("#test").val(),
product : $("#product").val(),
};
$.post('./index.php/test/deploy_test/', data,
function( answer ){
create_bar();
console.log( answer );
});
}
However, what I get back is the index.php
page, the html
itself, not the "helloworld"
string as expected. I have no idea what's going on. May someone please me? The output is:
<!DOCTYPE html>
<html>
<head>
<title>Deployer</title>
</head>
<body>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
Specify the return type in your POST in JS: dataType: json
You will need to set the correct header information on the server side before sending json_encode("helloworld")
so ajax can anticipate a json value before reading the answer. For example first lines could be :
header('Cache-Control: no-cache, must-revalidate'); // no cache
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json'); // json type
You will also need, like David suggested, to add dataType: json
in your ajax request.
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.