php不接受iOS JSON POST

时间:2013-10-06 23:25:38

标签: php ios json

不幸的是,我一直在寻找修复(或理由)7个小时,最后承认我需要一些帮助。

我刚刚开始重写ios的应用程序(来自android),我在ios中遇到了json。

我的JSON帖子动作;

      NSString *post = [[NSString alloc] initWithFormat:@"{'firstname':'%@' 'surname':'%@'      'yob':'%@' 'gender':'%@' 'hometown':'%@' 'phone':'%@' 'email':'%@' 'deviceid':'%@' 'regId':'%@'  'phonetype':'%@'}",[_FirstName text],[_Surname text],[_YOB text],[_Gender text],[_HomeTown text], [_PhoneNO text],[_Email text],[_deviceid text],[_regID text],[_phonetype text]];

  NSLog(@"PostData: %@",post);

  NSURL *url=[NSURL URLWithString:@"***"];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:url];

    [request setHTTPMethod:@"POST"];

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setValue:@"appplication/www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:postData];

    NSError *error = [[NSError alloc] init];

    NSHTTPURLResponse *response = nil;

    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSLog(@"Response code:%d", [response statusCode]);

    if ([response statusCode] >=200 && [response statusCode] <300)

    {

        NSString *responseData = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

        NSLog(@"Respinse ==> %@", responseData);

        SBJsonParser *jsonParser = [SBJsonParser new];

        NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];

        NSLog(@"%@",jsonData);

        NSInteger sucess = [(NSNumber *) [jsonData objectForKey:@"sucess"] integerValue];

        NSLog(@"%d",sucess);

        if (sucess==1)

        {

            NSLog(@"Signed up");

        }else {

            NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message@"];
       }
    }else {
       if (error) NSLog(@"Error: %@", error);
    }
}

和我的php;

<?php


 include_once("../php/sign_up/connect_db.php");
// array for JSON response
$response = array();

// check for required fields/
if (!empty($_POST['firstname']) && !empty($_POST['surname']) && !empty($_POST['email']) &&     !empty($_POST['phone']) && !empty($_POST['hometown']) && !empty($_POST['deviceid']) && !empty($_POST['yob']) && !empty($_POST['regId']) && !empty($_POST['gender'])) {

$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$hometown = $_POST['hometown'];
$deviceid = $_POST['deviceid'];
$phonetype = $_POST['phonetype'];
$yob = $_POST['yob'];
$regId = $_POST['regId'];
$gender = $_POST['gender'];

// include db connect class
//require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

   $result = mysql_query("SELECT *FROM User_signup WHERE (email = '".$email."')" ) or die(mysql_error());
 $existingemails = mysql_num_rows($result);

 if ($existingemails > 0) {

 $response["success"] = 0;
 $response["message"] = "Email address already exists";

 //echoing JSON response
 echo json_encode($response);

} 
else {



// mysql inserting a new row
$result = mysql_query("INSERT INTO User_signup(firstname, surname, email, phone, hometown, id, type, Yob, regid, gender) VALUES('$firstname', '$surname', '$email', '$phone', '$hometown', '$deviceid', '$phonetype', '$yob', '$regId', '$gender')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Thank you for signing up!";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "An Error has occurred, please try again later.";

    // echoing JSON response
    echo json_encode($response);
}
} 

   }else {
   // required field is missing
   $response["success"] = 0;
   $response["message"] = "Please check you have completed all required fields";

       // echoing JSON response
       echo json_encode($response);
      }

    ?>

这是JSON返回的;

    2013-10-07 00:03:59.465 ***[2517:c07] PostData: {'firstname':'ouyb' 'surname':'ouy' 'yob':'vbouv' 'gender':'GENDERouvy' 'hometown':'ouvy' 'phone':'ou' 'email':'vy' 'deviceid':'ilbuyv' 'regId':'obyouovy' 'phonetype':'uby'}

2013-10-07 00:03:59.645 ***[2517:c07] Response code:200

2013-10-07 00:03:59.645 ***[2517:c07] Respinse ==> {"success":0,"message":"Please check you     have completed all required fields"}

2013-10-07 00:03:59.646 ***[2517:c07] {

message = "Please check you have completed all required fields";

success = 0;

}

现在我的Android应用程序以相同的格式发布json数组,并被php完美接受。我不能为我的生活弄清楚什么是错的。

通过从php中删除检查“if empty”看来,php被调用并运行但是没有数据输入到数据库中,但是创建了一个新的空白行。对我来说听起来像应用程序没有发送它声称发送的内容。

任何正确方向的推动都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

JSON字符串用双引号括起来,而不是单引号,字典键/值对必须用逗号分隔。有关更多信息,请参阅json.org。

请注意,有一个NSJSONSerialization类,它可以从NSDictionary创建JSON数据。