【问题标题】:how to get json data from iphone post request如何从iphone post请求中获取json数据
【发布时间】:2010-09-07 08:26:57
【问题描述】:

我正在使用 JSON 框架开发 iPhone 应用程序,我正在调用 PHP 脚本来更新本地服务器上的 MySQL 数据库。使用这些代码:

NSString *jsonString = [sendData JSONRepresentation];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString*post = [NSString stringWithFormat:@"&json=%@", jsonString];
NSData*postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];

[request setURL:[NSURL URLWithString:@"http://localhost:8888/update.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:postData];

我想问一下:

什么是从该请求中获取数据的 PHP 脚本,以及如何将 JSON 数据解码为 PHP 对象以更新到数据库?

任何帮助将不胜感激。

【问题讨论】:

    标签: php iphone mysql cocoa-touch json


    【解决方案1】:

    我还没有用 iPhone 做这个,但看起来它只是:

    if(isset($_REQUEST['json']) && $_REQUEST['json']) {
        $jsonObj = json_decode($_REQUEST['json']);
        //mandatory sanitizing and verification here
        //PDO examples
        //$stmt = $db->prepare('INSERT ...');
        //$stmt->execute(array($jsonObj->userId, $jsonObj->specialData));
        //check statement execution
    }
    

    更多信息:

    http://php.net/json_decode

    http://php.net/pdo

    【讨论】:

      【解决方案2】:

      这里有一些代码行,您提供的信息有限

      <?php
      // get data
      $rawJsonData = $_POST;
      $decodedData = json_decode($rawJsonData);
      
      // .. do some parsing on $decodedData ..
      
      // save data
      $db = new Db();
      $db->insert('table', $decodedData);
      

      $decodedData 将是一个 PHP 数组,您可以按照您需要的任何方式对其进行处理,然后将其保存到数据库中。

      【讨论】:

        【解决方案3】:

        您将在变量 $_POST['json'] 中找到您的数据,您可以使用以下命令查看您通过 POST 收到的内容:

        <?php print_r($_POST); ?>
        

        一旦您确定了数据在哪里,您就可以使用以下方法从 JSON 传递到 PHP 数据:

        <?php $phpObj = json_decode($_POST['json']); ?>
        

        同样,您可以使用 print_r 查看数据的结构:

        <?php print_r($phpObj); ?>
        

        【讨论】:

          猜你喜欢
          • 2020-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-20
          • 1970-01-01
          • 1970-01-01
          • 2020-03-15
          • 2016-11-17
          相关资源
          最近更新 更多