繁体   English   中英

通过 Ajax 将 JS object(关联数组)传递给 PHP 不起作用

[英]Passing JS object (associative array) via Ajax to PHP not working

我正在尝试将动态创建的 JS object(关联数组)传递给 PHP / MySQLi 查询。
- 当我将 JS object ( transferData ) 写入控制台时,它会按预期显示(见下文)。
- 当我分别测试 PHP / MySQLi 查询时,它也可以工作。
- 因此,我假设我的问题在于我用来将 JS object 传递给 PHP / ZC1EE33629547F540ECDF7489 的 Ajax 调用

Can someone tell me how the correct Ajax call should look like here (eg using JSON etc.) or what I have to change on the PHP / MySQLi side?

我的 JS object:

0: {vId: "04567901", rId: "DE-002"}
1: {vId: "04567902", rId: "DE-005"}
2: {vId: "04567903", rId: "DE-007"}
length: 3
__proto__: Array(0)

我的 jQuery / Ajax:

$('#btnConfirm').click(function() {
    $.ajax({
        type: 'POST',
        url: 'updateIds.php',
        data: {
            transferData: transferData
        },
        success: function(result){
            $('#modalSuccess').modal('show');
        }
    });
});

我的 PHP / mySQLi:

$postData = $_POST; 
$transferData = $_POST['transferData'];

$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
    die("Connection Error: " . $conn->connect_error);
}   
$stmt = $conn->prepare("UPDATE myTable l SET l.rId = ? WHERE l.vId = ?");
foreach($transferData as $vId => $rId) {
    $stmt->bind_param('ss', $rId, $vId);
    $stmt->execute();
}

$stmt->close();
$conn->close(); 

更新:
我的重点是 Ajax 调用,因为我认为数据没有到达 PHP 页面是有原因的。

非常感谢您对此的任何帮助,汤姆

只需像这样在 php 中获取您的数据:

$postData = file_get_contents("php://input"); 
$transferData = json_decode($postData, true)['transferData'];

When you use the POST request is better to indicate the data type you're expecting from the server-side use " dataType " in your ajax request, and then parse the data to a valid javascript object in your success handler using JSON.parse( ) .

$('#btnConfirm').click(function() {
    $.ajax({
        type: 'POST',
        url: 'updateIds.php',
        dataType: 'JSON', // I'm expecting a json response
        data: {
            transferData: transferData
        },
        success: function(result){
            // parse json
            const data = JSON.parse(result);

            $('#modalSuccess').modal('show');
        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM