簡體   English   中英

將javascript數組傳遞給php

[英]passing javascript array to php

我正在嘗試學習如何將數組傳遞給php,警報('成功')確實顯示但我不認為該值傳遞給php,因為php內的警報沒有顯示。

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      function submit(){
        var TableData = {"table1":"sample1","table2":"sample2","table3":"sample3"};
        var Data = JSON.stringify(TableData);
        $.ajax({
          type: "POST",
          url: "getInfo.php",
          data: {pTableData : Data},
          success: function(){
            alert('Success');
          }//success
        });
    }//submit();
    </script>
  </head>
  <body>
    <div>
      <button type = "button" onclick = "submit();">SUBMIT</button>
    </div>
  </body>
</html>

我的PHP代碼:

<?php
  $table = json_decode($_POST['pTableData']);
  $msg = $table['table1'];
  echo '<script>alert("';
  echo $msg;
  echo '");</script>';
?>

非常感謝你!

您需要將響應檢索到成功函數中。 同樣在php中你必須傳遞$table = json_decode($_POST['pTableData'], true); 否則它返回為對象而不是數組

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      function submit(){
        var TableData = {"table1":"sample1","table2":"sample2","table3":"sample3"};
        var Data = JSON.stringify(TableData);
        $.ajax({
          type: "POST",
          url: "get_info.php",
          data: {pTableData : Data},
          success: function(result){ //retrieve data
            alert('Success');
            alert(result); //alert it
          }//success
        });
    }//submit();
    </script>
  </head>
  <body>
    <div>
      <button type = "button" onClick = "submit();">SUBMIT</button>
    </div>
  </body>
</html>

PHP代碼:

<?php
  $table = json_decode($_POST['pTableData'],true);
  $msg = $table['table1'];  
  echo $msg;  
?>

好吧,據我所知,您希望您的PHP腳本(在后端)向您顯示警報。 因此,這是不可能的,因為alert() - 是一種JavaScript方法,它應該在用戶瀏覽器內部進行評估,以便查看由PHP腳本引起的警報。 此外,不要混淆back-endfront-end定義。 正如我已經說過的,PHP - 是一種后端語言,所以它不能用於直接與最終用戶交互。 有這種需求的JavaScript和HTML語言(前端)。

嘗試將JavaScript代碼修改為以下內容:

$.ajax({
    type: "POST",
    url: "getInfo.php",
    data: {pTableData : Data},
    dataType: "html",
    success: function(data){
        $('body').append(data);
    } //now it will insert the code your PHP script produced on a back-end 
      //onto the page's body, so, you are gonna see an alert only if the PHP 
      //have actually echoed a correct HTML back to the JavaScript on that context
});

您可能也對console.log() 這樣的函數感興趣( 它不是JavaScript標准 - 它的實現取決於您要使用的瀏覽器;它適用於Webkit,Gecko和最新的Microsoft瀏覽器 。順便說一句,它是說不應該在已部署的項目中使用 )。 因此,您可以將您的success方法修改為console.log(data); 完成ajax請求后,打開開發人員控制台(默認情況下在大多數WebKit瀏覽器中按Ctrl + Shift + C),看看會發生什么。

暫無
暫無

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

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