簡體   English   中英

如何將數組從Javascript傳遞給PHP

[英]How to pass Array from Javascript to PHP

我有一個函數,每次單擊按鈕到localStorage時保存一個數組。按鈕將被多次單擊,我需要將此數組列表以某種方式放入PHP,這是在該文件的另一頁上。

謝謝

a.js(這個函數偵聽頁面的onLoad)

    function doFirst(){
    var button = document.getElementById("button");
    button.addEventListener("click", save, false);

    var buttons = document.getElementById("clear");
    buttons.addEventListener("click", clear, false);

    var buttonss = document.getElementById("submittodb");
    buttonss.addEventListener("click", toPHP, false);

        $.ajax({
            method: 'post',
            dataType: 'json',
            url: 'edit.php',
            data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
            success: function() {//some code to handle successful upload, if needed
            }
        });

        }

        function save(){

        var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

        var newItem = {
           'num': document.getElementById("num").value,
            'methv': document.getElementById("methv").value,
            'q1': document.getElementById("q1").value,
            'q2':document.getElementById("q2").value,
            'q3':document.getElementById("q3").value,
            'q4':document.getElementById("q4").value,
            'comm':document.getElementById("comm").value,

        };
        oldItems.push(newItem);

        localStorage.setItem('itemsArray', JSON.stringify(oldItems));}


edit.php


$parsed_array = json_decode($_POST['items']);

and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9

為了將此數組傳遞給PHP,您需要:

  1. JSon編碼它
  2. 向PHP發出AJAX或POST請求
  3. 將傳遞的數組解析為PHP數組

如果你正在使用jQuery (如果你不是你應該開始 - 這是非常方便的工具)步驟(1)和(2)就像

$.ajax({
    method: 'post',
    dataType: 'json',
    url: 'the URL of PHP page that will handle the request',
    data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
    success: function() {//some code to handle successful upload, if needed
    }
});

在PHP中,您可以使用just解析傳遞的數組

$parsed_array = json_decode($_POST['items']);

{ items: oldItems }$_POST['items']之間存在直接聯系。 您在javascript調用中為參數賦予的變量名稱將是$_POST數組中鍵的名稱。 因此,如果您只是使用data: oldItems javascript中的data: oldItems ,您將把所有實體分散在$_POST數組周圍。

更多關於$ .ajaxjson_decode的參考。

您可以創建一個AJAX函數(使用jQuery)並將JSON數據發送到服務器,然后使用PHP函數/方法對其進行管理。

基本上,您需要將數據從客戶端(瀏覽器)發送回數據庫托管的服務器。

  1. 調用JSON.stringify(oldItems); 創建json字符串

  2. 使用AJAX執行POST請求。

可能最簡單的方法是使用jQuery:

$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
  // it worked.
});

暫無
暫無

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

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