问题描述
我不知道什么是处理Ajax使用jQuery调用的最好方法?现在我在做类似如下:
I'm wondering what is the best method to handle AJAX calls with jQuery? Right now I'm doing something like following:
$("#test").live('click', function(){
// Process form
$.ajax({
type: "post",
url: "test.php",
success: function(html){
if(html.success == 0) {
alert('Error');
} else {
var obj = $.parseJSON(html.rows);
$("#success").html(obj[0].name);
}
},
dataType:'json'
});
return false;
});
在test.php的文件,我检查,如果请求是一个AJAX请求。如果它是一个Ajax请求我运行一个数据库查询,得到一些数据(这部分是不是在这个问题很重要,我认为):
In test.php file, I'm checking if request is an AJAX request. If it's an AJAX request I'm running a database query to get some data (this part isn't important in this question, I think):
// query goes here
if(mysql_num_rows($query) > 0 ) {
$result['success'] = 1;
$result['data'] = json_encode($data);
} else {
$result['success'] = 0;
}
现在我想知道如果我的方法是最好的?仅供参考我使用KohanaPHP目前的框架,所以我想不会打破MVC的规则。如果我做错了,你有什么提示和建议如何处理控制器AJAX调用?
Now I'm wondering if my method is the best possible? FYI I'm using KohanaPHP framework currently, so I want to not break MVC "rules". If I'm doing it wrong, do you have any tips and suggestions how to handle AJAX calls in controllers?
问候,汤姆
推荐答案
你有什么好看在这里,虽然我不认为你需要一个 $。parseJSON()
那里,它应该已经是一个对象在该点,这应该工作:
What you have looks good here, though I don't think you need a $.parseJSON()
there, it should already be an object at that point, this should work:
$("#success").html(html.rows[0].name);
作为一个侧面说明,从可读性/可维护性的角度来看,我会重命名 HTML
参数是数据
,像这样的:
As a side note, from a readability/maintainability perspective, I'd rename your html
argument to be data
, like this:
success: function(data) {
这纯粹是preference,但使用 HTML
时,它是一个HTML类型的响应,而数据
或别的东西时,它的JSON /已经你期待的对象让事情有点更容易阅读为外人道。
This is purely preference, but using html
when it's an HTML type response, and data
or something else when it's JSON/already an object you're expecting keeps things a bit easier to read for outsiders.
这篇关于jQuery的AJAX调用,如何处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!