在过去的两年里,我一直在使用codeigniter,并且已经成为一个超级粉丝,但是在过去的一年里,我发现自己写的javascript比php还多。
一开始,我会用php编写所有东西,但现在我发现自己一直在使用$.ajax。我有点像在javascript和php之间重复我自己。
我知道ci确实给了您对ajax的一些很好的控制,但是我仍然有两个写大量javascript,如果可能的话,我想合并。
我想我要找的是一个与jquery的$.ajax紧密集成的php框架。
最佳答案
我在javascript中使用这段代码。后端方面的事情是在mvc类型的组织中组织的,因此影响一个模块的事情通常被组合在一起。一般来说,我也会为一个单独的模型创建一个sperate模块,但是在某些情况下,您可能会偏离这个原则。
我的设置是在后面使用symfony,在前面使用纯jquery。有一些方法可以使这一部分自动化,比如http://javascriptmvc.com/,我发现它在很多方面都有局限性。下面是我集成php和jquery的工作流程。
PHP
执行一段代码并将其包装在try/catch块中。这样错误消息就可以传播到前端。在这方面,此方法有助于将异常转换为可读错误。(从json调试)。
try {
//... execute code .. go about your buisness..
$this->result = "Moved " . count($files) . " files ";
// result can be anything that can be serialized by json_encode()
} catch (Exception $e) {
$this->error = $e->getMessage() . ' l: ' . $e->getLine() . ' f:' . $e->getFile();
// return an error message if there is an exception. Also throw exceptions yourself to make your life easier.
}
// json response basically does something like echo json_encode(array("error" => $this->error, "result" => $this->result))
return $this->jsonResponse();
对于错误处理,我经常使用这个来分析错误。
public function parseException($e) {
$result = 'Exception: "';
$result .= $e->getMessage();
$trace = $e->getTrace();
foreach (range(0, 10) as $i) {
$result .= '" @ ';
if (!isset($trace[$i])) {
break;
}
if (isset($trace[$i]['class'])) {
$result .= $trace[$i]['class'];
$result .= '->';
}
$result .= $trace[$i]['function'];
$result .= '(); ';
$result .= $e->getFile() . ':' . $e->getLine() . "\n\n";
}
return $result;
}
javascript端
/**
* doRequest in an ajax development tool to quickly execute data posts.
* @requires jQuery.log
* @param action (string): url for the action to be called. in config.action the prefix for the url can be set
* @param data (object): data to be send. eg. {'id':5, 'attr':'value'}
* @param successCallback (function): callback function to be executed when response is success
* @param errorCallback (function): callback function to be executed when response is success
*/
jQuery.doRequest = function (action, data, successCallback, errorCallback) {
if (typeof(successCallback) == "undefined") {
successCallback = function(){};
}
if (typeof(errorCallback) == "undefined") {
errorCallback = function(data ){
alert(data.error);
};
}
jQuery.log(action);
jQuery.post(action, data, function (data, status)
{
jQuery.log(data);
jQuery.log(status);
if (data.error !== null || status != 'success') {
// error handler
errorCallback(data);
} else {
successCallback(data);
}
},'json');
};
注意:如果将错误回调与pNotify