Good day!
I'm learning to create AJAX calls to PHP scripts.
Basically, I want to find the best solution to handle AJAX calls. In this question you can find my client-side part of the code.
Basically, I'd like to verify my knowledge here and if I'm wrong, get any tips how to make it correct way.
So... I'm using KohanaPHP framework (but also going to learn ZendFramework). I created a test controller with following code:
public function __construct()
{
if (request::is_ajax()) {
$this->auto_render = FALSE;
header('content-type: application/json');
}
}
public function index()
{
$result['success'] = 1;
$test_model = new Test_Model;
$items = $test_model->get_test_rows();
foreach($items as $item):
$rows[] = $item;
endforeach;
$result['rows'] = json_encode($rows);
if (request::is_ajax()) {
echo json_encode($result);
}
}
Now I got few questions related to this c开发者_JAVA百科ode. Let me ask them.
1) In thread mentioned above I was told I do not have to use $.parseJSON();
function and I can use data.rows[0]name
instead. Unfortunately, it does not work. For the is't not a big problem, I can use $.parseJSON();
but I'd like to know if there's any bug in my PHP code?
2) I'm trying to learn good practices and techniques and I'm try to not violate MVC rules. I have a MVC related question. Is it possible to use echo()
in controllers? You may notice I'm using it to return JSON encoded data.
To answer question (2): Yes, it is normally bad form to echo
in the controller. I'd even go as far to say it's bad form to build any sort of string the controller either.
However, in the case where all that's being output is json, I think it's simply easier, and more concise to just echo json_encode($results);
If you really want to be an MVC purist, you can always create a file that does nothing but echo json(...);
.
1) jQuery.ajax
function is smart enough to parse your JSON response provided that you tell it that you are returning a JSON-enconded object. Here is how your backend Kohana can tell your frontend jQuery that they are talking in JSON, in your Controller:
$this->request->headers['Content-Type'] = 'application/json';
2) There's nothing wrong with using echo
but since you are using Kohana, the recommended way of returning response to the browser client, from inside a controller, is:
$this->request->response = json_encode($result);
In your code:
$result['rows'] = json_encode($rows);
if (request::is_ajax()) {
echo json_encode($result);
}
I would say it should be:
$result['rows'] = $rows;
if (request::is_ajax()) {
echo json_encode($result);
}
I do not know what the purpose of the is_ajax is, but that may be an unnecessary check. But what was probably happening was that you were encoding the rows then encoding the entire result set. So when it came to parsing and you did the parseJSON, well you would have to do that again for the rows index of the array.
精彩评论