iPhone App / JSON - 将数据发布到远程数据库 [英] iPhone App/JSON - Posting Data to Remote Database

查看:193
本文介绍了iPhone App / JSON - 将数据发布到远程数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iPhone应用程序,使用ASIHTTPRequest将数据发布到php文件,然后使用sql相应地更新数据库。

I have an iPhone app that uses ASIHTTPRequest to post data to a php file, which then uses sql to update the database accordingly.

我保持警惕的是什么读到我应该用JSON格式编码我发布的数据。有人可以向我解释这一点吗?我为什么要用JSON格式编码?有什么好处,需要... ..

What's bugging me is I keep reading that I should encode my posted data in JSON format. Can somebody explain to me the point in this? Why should I encode in JSON format? What are the benefits, needs for this..

编辑:

以下是我发布数据的方式:

Here is how I am posting my data:

-(void) postToDB:(NSString*) msg{
    NSString *myphp = @"http://localhost:8888/databases/test.php";
    NSURL *url = [NSURL URLWithString:myphp];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:msg forKey:@"message"];
    [request setDelegate:self];
    [request startAsynchronous];
}


推荐答案

将数据封装在JSON中结构有助于与服务器创建结构化通信协议。根据您的需要不进行此操作,例如,请查看JSON-RPC的规范。这允许您拥有一个完全定义的协议来交换数据,其中方法总是以相同的方式传递,错误总是以相同的方式返回。

Encapsulating your data in a JSON structure helps creating a structured communications protocol with your server. Without going as far as this depending on your needs, take a look at the specs for JSON-RPC for example. This allows you to have a fully-defined protocol for exchanging data, where methods are always passed the same way, errors are always returned the same way too.

使用严格来说,JSON,JSON-RPC,SOAP或任何其他信封绝不是强制性的。这只是通过电线标准化通信的一种很好的做法。

The use of JSON, JSON-RPC, SOAP, or any other "envelope" is, strictly speaking, never mandatory. It's just a good practice of standardizing communications over the wires.

另外,我不知道 setPostValue:ForKey:在需要时自动转义字符,但想象你发送一个GET到 HTTP://whatever/get.php昵称=尼克和放大器;有特殊字符@&放大器;密码= qzerty ?。
这里发生了什么?您的PHP脚本将无法正确解析昵称和密码字段。
借助JSON框架在JSON中封装数据(您可以在一行代码中完美地将NSString字典转换为JSON结构)有助于防止出现这种情况。

Also, I don't know if setPostValue:ForKey: automatically escapes characters when needed, but imagine you're sending a GET to http://whatever/get.php?nickname=nick&with?special@chars&password=qzerty. What happens here? your PHP script won't be able to parse the "nickname" and "password" fields correctly. Encapsulating your data in JSON with the help of a JSON framework (you can turn a NSString dictionary to a JSON structure flawlessly in a single line of code) helps preventing this kind of situation.

这篇关于iPhone App / JSON - 将数据发布到远程数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆