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

时间:2022-12-26 15:43:01

I get the following error when i try to get data. In the internet i read that its because the php script is invalid and don't return json data. But the php script runs fine and outputs the right data.

我尝试获取数据时收到以下错误。在互联网上我读它,因为PHP脚本无效,不返回json数据。但php脚本运行正常并输出正确的数据。

Error Message :

错误信息 :

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Error Domain = NSCocoaErrorDomain Code = 3840“JSON文本没有以数组或对象开头,并且选项允许未设置片段。” UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}

I tried to allow fragments but then i get just another error message.

我试图允许片段,但后来我得到另一个错误消息。

Here is the swift code where i try to get the data :

这是我尝试获取数据的快速代码:

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()

and this is the important part of the php file :

这是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 returns this when i print it: Array ( [status] => 200 [userFirstName] => Paul [userLastName] => Heinemeyer [userEmail] => paul_heine [userId] => 63 )

当我打印它时,$ returnValue返回:Array([status] => 200 [userFirstName] => Paul [userLastName] => Heinemeyer [userEmail] => paul_heine [userId] => 63)

1 个解决方案

#1


2  

When you properly format your PHP code, you will see, that in the else part you have

正确格式化PHP代码后,您会看到,在您拥有的其他部分中

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

which results in

结果

failed{...}

As the error message already says, this "JSON text did not start with array or object ..."

正如错误消息所说,这个“JSON文本不是以数组或对象开头......”

Maybe there is similar output for the other if part.

如果是另一个,也许有另一个类似的输出。

#1


2  

When you properly format your PHP code, you will see, that in the else part you have

正确格式化PHP代码后,您会看到,在您拥有的其他部分中

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

which results in

结果

failed{...}

As the error message already says, this "JSON text did not start with array or object ..."

正如错误消息所说,这个“JSON文本不是以数组或对象开头......”

Maybe there is similar output for the other if part.

如果是另一个,也许有另一个类似的输出。