尝试从php脚本获取Json数据时出错

问题描述:

当我尝试获取数据时,出现以下错误。在互联网上我读到它,因为PHP脚本是无效的,不返回JSON数据。但PHP脚本运行良好,并输出正确的数据。尝试从php脚本获取Json数据时出错

错误消息:

错误域= NSCocoaErrorDomain代码= 3840“JSON文本不与阵列或对象和选项,允许片段未设置启动”。的UserInfo = {NSDebugDescription = JSON文字不与数组或对象和期权开始允许未设定片段。}

我试图让碎片,但后来我得到的只是另一个错误信息。

这里是SWIFT代码,我试图让数据:

let myUrl = NSURL(string: "http://xxxxxxxxxxx.xxx/xxxxxxxx.php") 

let request = NSMutableURLRequest(URL: myUrl!) 
request.HTTPMethod = "POST" 

let postString = "userEmail=\(userEmail!)&userPassword=\(userPassword!)" 

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 

NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in 

    dispatch_async(dispatch_get_main_queue()) 
    { 
     if(error != nil) 
     { 
      var alert = UIAlertController(title: "Achtung", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) 

      let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) 

      alert.addAction(action) 

      self.presentViewController(alert, animated: true, completion: nil) 
     } 
     print("1") 
     do { 
      let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary 

      if let parseJSON = json { 

       let userId = parseJSON["userId"] as? String 
       if(userId != nil) 
       { 
        print("SUCESS FUCKER") 
        let mainView = self.storyboard?.instantiateViewControllerWithIdentifier("main") as! FlickrPhotosViewController 

        let mainPageNavi = UINavigationController(rootViewController: mainView) 
        //open mainView 
        let appdele = UIApplication.sharedApplication().delegate 
        appdele?.window??.rootViewController = mainPageNavi 


       } else { 
        let userMassage = parseJSON["message"] as? String 
        let myAlert = UIAlertController(title: "Alert", message: userMassage, preferredStyle: UIAlertControllerStyle.Alert); 

        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) 
        myAlert.addAction(okAction); 
        self.presentViewController(myAlert, animated: true, completion: nil) 

       } 

      } 
     } catch{ 
      print(error) 
      print("FAILED CATCHED") 
     } 

    } 
}).resume() 

,这是PHP文件的重要组成部分:

$userSecuredPassword = $userDetails["user_password"]; 

$userSalt = $userDetails["salt"]; 

if($userSecuredPassword === sha1($userPassword . $userSalt)) 
{ 
    $returnValue["status"]="200"; 

    $returnValue["userFirstName"] = $userDetails["first_name"]; 

    $returnValue["userLastName"] = $userDetails["last_name"]; 

    $returnValue["userEmail"] = $userDetails["email"]; 

    $returnValue["userId"] = $userDetails["user_id"]; 
} else { 
    $returnValue["status"]="403"; 

    $returnValue["message"]="User not found"; 

    echo "failed"; 

    echo json_encode($returnValue); 

    return; 
} 



echo json_encode($returnValue); 

$的returnValue返回此当我打印出来: 阵列([状态] => 200 USERFIRSTNAME] =>保罗[USERLASTNAME] => Heinemeyer [USEREMAIL] => paul_heine [用户id] => 63)

+1

几个无关的观察:1.你真的应该是百分比转义你添加到发布请求正文的值(例如,如果你的密码有一个'&'或'+'字符,它不会被捕获正确)。 2.你可能想在php中包含一个'header(“Content-Type:application/json”);'。这不是技术上的要求,但这是一个很好的做法。 3.您还应该将原始请求的“Content-Type”设置为“application/x-www-form-urlencoded”。 4.考虑使用Alamofire让你脱离正确创建请求和解析响应的杂草。 – Rob

当你正确地格式化PHP代码,你会看到,在其他部分你有

echo "failed"; 
echo json_encode($returnValue); 

导致

failed{...} 

随着错误消息已经指出,这种“JSON文字不与数组或对象开始。 ..“

也许有类似的输出,如果其他部分。

+0

Sry,但我不明白你的解决方案,因为这两行代码我进入了一个失败的块? @Olaf Dietsche –

+0

这不是一个解决方案,只是一个观察,在其他情况下,PHP输出确实以“失败”开始,它既不是数组的开始[',也不是对象的开始'{' 。所以对于其他情况,删除'echo“失败”'。 –

+0

要充分调查这一点,您必须在客户端输出响应。在那里你会看到,问题是什么以及错误输出来自哪里。从你的问题中的部分代码,我可以推断出只有部分答案。 –