You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift使用URLRequest POST向PHP传递数组失败问题求助

问题:URLRequest POST传递数组到PHP失败

我通过URLRequest的POST方法向服务器传递数组时无法成功,发送字符串可以正常工作,但数组数据在PHP端获取不到。

正常运行的字符串传递Swift代码:

func getData() {
    
    pageid = 1
    
    var request = URLRequest(url: URL(string: "http://localhost/index.php")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
    request.httpMethod = "POST"
    
    let postString = "page=" + String(pageid);
    request.httpBody = postString.data(using: .utf8)
    
    URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
        
        do {
        
            let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>
            
            let itemsArray = response["items"] as! [AnyObject]
            
            for itemObj in itemsArray {
                print(itemObj)
            }
        } catch {
        
        }
        
    }).resume();
}

需要传递的数组:

var ids: [Int] = [1, 5, 8]

我尝试用let postString = "page=" + String(ids.description)传递但无效,PHP代码如下:

<?php
    $pageid = $_POST['page'];
    ....
?>

解决方案1:使用表单数组格式传递

这种方式适配PHP默认的表单数组解析规则,需要将参数名设为page[],并逐个拼接数组元素。

Swift代码修改:

func getData() {
    let ids: [Int] = [1, 5, 8]
    
    var request = URLRequest(url: URL(string: "http://localhost/index.php")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
    request.httpMethod = "POST"
    // 声明表单编码类型
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    
    // 拼接成page[]=1&page[]=5&page[]=8的格式
    let postComponents = ids.map { "page[]=\($0)" }.joined(separator: "&")
    request.httpBody = postComponents.data(using: .utf8)
    
    URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
        do {
            guard let data = data else { return }
            let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
            
            if let itemsArray = response["items"] as? [Any] {
                for itemObj in itemsArray {
                    print(itemObj)
                }
            }
        } catch {
            print(error.localizedDescription)
        }
    }).resume()
}

对应PHP代码:

<?php
// $_POST['page']会被解析为数组
$pageIds = $_POST['page'];
// 遍历数组处理数据
foreach ($pageIds as $id) {
    echo "ID: " . $id . "<br>";
}
// 后续业务逻辑
....
?>

解决方案2:使用JSON格式传递(推荐)

直接将数组序列化为JSON字符串传递,PHP端读取原始POST数据并解析JSON,这种方式更适合复杂数据结构的传递。

Swift代码修改:

func getData() {
    let ids: [Int] = [1, 5, 8]
    
    var request = URLRequest(url: URL(string: "http://localhost/index.php")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
    request.httpMethod = "POST"
    // 声明JSON编码类型
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    do {
        // 将数组包装为字典并序列化为JSON数据
        let jsonData = try JSONSerialization.data(withJSONObject: ["page": ids], options: [])
        request.httpBody = jsonData
    } catch {
        print(error.localizedDescription)
        return
    }
    
    URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
        do {
            guard let data = data else { return }
            let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
            
            if let itemsArray = response["items"] as? [Any] {
                for itemObj in itemsArray {
                    print(itemObj)
                }
            }
        } catch {
            print(error.localizedDescription)
        }
    }).resume()
}

对应PHP代码:

<?php
// 读取原始POST数据流
$rawData = file_get_contents('php://input');
// 解析JSON为关联数组
$postData = json_decode($rawData, true);
// 获取page数组
$pageIds = $postData['page'];

foreach ($pageIds as $id) {
    echo "ID: " . $id . "<br>";
}
// 后续业务逻辑
....
?>

内容的提问来源于stack exchange,提问作者strawberrygirl20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:55:15