我正在使用 PHP/jQuery/MySQL 为我的 friend 建立一个小型酒店网站。与典型的 CRUD 应用程序一样,它会有表格和报告。我有一个 PHP 框架来呈现表单并使用 Ajax 保存它们。现在我需要在保存数据项时更新网页上的元素。由于这是一个小项目,我会采用在 Ajax 响应中发送 HTML 并将响应嵌入网页的简单方法。但我决定使用 JSON,以便我可以将框架扩展到其他项目。以下是我的设计思路:
{
'status':'', /*status like success/fail */
'message':'', /*a status message or sting will be more helpful in case of failure */
'data':'', /*arbitrary data*/
'datatype':'' /*is it JSON or HTML or javascript( or some thing else?)*/
}
基于响应,jQuery 将更新/管理网页元素。我是不是遗漏了一些东西,还是我在这个设计中完全错了。
最佳答案
我不会在那里有状态,而是会考虑使用 HTTP 状态代码来报告状态。在 PHP 中,如果收到并发出,可以使用 header()
传回 400。如果你再传回 200 就万事大吉了。
然后在 jQuery 中你可以这样做:
$.getJSON( 'http://someUrl/action.php' ).success( function() {
alert( 'success' );
} ).error( function() {
alert( 'fail' );
} );
对于您的 JSON 结构,我将保留您拥有的所有其他内容。
{
'message': '', /*a status message or sting will be more helpful in case of failure */
'datatype': '', /*is it JSON or HTML or javascript( or some thing else?)*/
'data': {} /*arbitrary data*/
}
希望对您有所帮助。
关于javascript - 需要为 Ajax 驱动的 webapp 创建一个小的 JSON 结构的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6812381/