alle/kohana-jsend

此包已被弃用且不再维护。未建议替代包。

Kohana 3.3 的 JSend 模型(一致的 JSON 响应)

安装: 560

依赖项: 0

建议者: 0

安全: 0

星标: 1

关注者: 2

分支: 4

类型:kohana-module

dev-master 2014-01-07 14:31 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:29:37 UTC


README

作者:Kemal Delalic

参见:http://labs.omniti.com/labs/jsend

示例多场景操作

public function action_create()
{
	$json = new JSend;
	$post = new Model_Post;
	
	if ($this->request->method() === Request::POST)
	{
		try
		{
			$post->values($this->request->post())
				->create();
				
			$json->data('post', $post); // success is default anyways
		}
		catch (ORM_Validation_Exception $e)
		{
			// Errors are extracted
			// from ORM_Validation_Exception objects
			$json->status(JSend::FAIL)
				->data('errors', $e); 
		}
		catch (Exception $e)
		{
			// Exception message will be extracted
			// and status will be set to JSend::ERROR
			// because only error responses support messages
			$json->message($e); 
		}
	}
	
	$json->render_into($this->response);
}

示例数据检索操作

public function action_posts()
{
	// Success is the default JSend status
	JSend::factory(array('posts' => ORM::factory('post')->find_all()))
		->render_into($this->response);
}

示例 jQuery 响应处理

$.post('/posts', {from: 1337}, function(jsend) {
	if (jsend.status === 'success') {
		$.each(jsend.data.posts, function(key, post) {
			$('#posts').append('<a href="' + post.url + '">' + post.title + '</a>')
		})
	}
	else if (jsend.status === 'fail') {
		$.each(jsend.data.errors, function(field, error) {
			$('#form').find('#' + field).append('<span class="error">' + error + '</span>')
		})
	}
	else {
		$('#posts').addClass('error').text('Internal error: ' + post.message)
	}
});

这也可以在更“全局”的级别上通过重写或添加 jQuery 方法来覆盖。