簡體   English   中英

將數據從 javascript forEach 循環中的 php 數組發送到 Z2705A83A5A06659CCE34Z5839 的 url 調用

[英]send data from php array in javascript forEach loop to url of ajax call

我正在嘗試遍歷 php 中的 mysql 查詢的結果,查詢的 output 是一個類似於 [10201,102] 的數組。 I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. 目標是獲取 id 並在另一個頁面上的 sql 查詢中使用它來更改我們數據庫中 id 的日期。

mysql查詢:

<?php
        // sql query for # print all open orders function
        $sql = "SELECT Order_PID
                FROM `Order`
                WHERE SHIPDATE IS NULL
                AND Address1 IS NOT NULL;";
        $query = mysqli_query($conn, $sql);
        while ($row = mysqli_fetch_assoc($query)) { 
                $order[] = $row['Order_PID'];
        }
?>

javascript function:我正在嘗試使用 forEach function 來遍歷數組的結果。

$('button#printOpenOrders').on('click', function(e) {
    if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
        e.preventDefault();
        // prints all open orders
        window.open("/resources/scripts/allOpenPDF.php");
        var arr = $order;
        arr.forEach(function(id) { // <====this function
            $.ajax({
            url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
            datatype : "string",
            success : function(data) {
                location.reload(true);
                }
            })
        })
     }
});

如果它有幫助是我的回調腳本

<?php 

    // login validation
    session_start();
    if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
        $url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
        header("Location: ../../index.php");
    }
    // establish connection to database
    include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
    $conn = openConnection();

    // capture id 
    $id = $_GET['id'];

    $pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
    $pendingDate = date_format($pendingDate, "Y-m-d H:i:s");

    $sql = $conn->prepare("UPDATE       `Order`
                           SET          SHIPDATE = ?
                           WHERE        Order_PID = ?");
    $sql->bind_param("si", $pendingDate, $id);
    $sql->execute();

    echo "success";

    closeConnection($conn);

?>

如果我的部分代碼沒有意義,那么我是新手,我正在利用我目前有限的知識將所有這一切一起弗蘭肯斯坦。 任何朝着正確方向的輕推都會非常有幫助。

您可以 output $order 變量內容,但您需要使用 PHP 並且您必須使用 json 格式對其進行編碼,因此這實際上可以工作:

var arr = <?PHP echo json_encode($order); ?>;

但它很容易出錯,語法不是很好閱讀,如果該變量以某種方式變為您不期望的格式,它可能會導致另一個 JavaScript 語法錯誤。

但在我看來,最好的方法是發出 AJAX 請求並獲取這些訂單 IDS,然后您可以創建另一個 AJAX 請求來發送所有這些訂單 IDS,因此您不需要.forEach 的東西和您的邏輯處理多個訂單需要修改以適應這些變化。

但是由於您已經在 PHP 中擁有這些 IDS,我的意思是存儲在 $order 變量中,您可以對其進行編碼並在一個請求中一次將所有 id 發送給它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM