簡體   English   中英

Javascript POST 不起作用 - 將 Javascript 數組發送到 PHP

[英]Javascript POST not working - Sending Javascript array to PHP

我知道在 SO 和網絡上有相當多的條目,但是我無法開始工作 - 任何幫助將不勝感激。

所以我在 Javascript 中有一個數組,我試圖將其傳遞給 PHP。

我有一個小的 JS 函數來首先發布它,所以:

function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}

然后在頁面下方,我有 PHP:

<?php 
    $myval = $_POST['variable'];
    print_r ($myval);
    ?>

*印刷品就在那里供我檢查。

任何想法 - 僅供參考,我正在使用 MAMP,所以它的 localhost:8888/index.php。 這是否會導致 URL 不正確的問題?

謝謝。

您對 ajax 的工作方式有誤解。 盡管 jquery 使它變得容易,但它仍然不是自動的。 你應該找到一個關於 ajax 和 jquery 的教程,但是如果你只想將一個數組發送到 php 並在屏幕上看到輸出,這樣的事情會起作用:

索引.php

<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //attach to the button a click event
    $('#btn').click(function(){
            //get the value from the textbox
        var txt=$('#txt').val();
            //if txt is blank, alert an error
        if(txt == ''){
            alert("Enter some text");
        } else {
                    //send txt to the server
                    //notice the function at the end. this gets called after the data has been sent
            $.post('catcher.php', {'text':txt}, function(data){
                            //now data is an object, so put the message in the div
                $('#response').text(data.message);
            }, 'json');
        }
    });
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;">&nbsp;</pre>
</body>
</html>

捕手.php:

<?php
//if something was posted
if(!empty($_POST)){
    //start an output var
    $output = array();

    //do any processing here.
    $output['message'] = "Success!";

    //send the output back to the client
    echo json_encode($output);
}

最好使用 2 個文件,一個供用戶加載以啟動 ajax 調用,一個頁面用於處理 ajax 調用。 發送數組的工作原理相同,只是將獲取文本框值替換為發送數組。

這是打開頁面時發生的情況( index.php

  1. index.php發出GET請求並返回內容。 $_POST數組中沒有值,因此您的print_r()行不執行任何操作。
  2. 執行 Javascript,通過 AJAX 向index.php發送POST請求。 請注意,這是一個全新的請求,與原始GET分開。 $_POST數組將在請求上填充,但響應將被丟棄。

希望這將說明您可以做什么。

ajax.php

<?php echo json_encode($_POST);

索引.php

<script>
var toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
    variable: toSearchArray
}, function(data) {
    alert(data); // here you will see the result of the ajax.php script
});
</script>

而不是將變量 toSearchArray 聲明為數組。 將其視為一個 javascript 對象。 var toSearchArray = {}。

好吧,我認為這不是數組的正確方法,看到您需要在 javascript 中使用 JSON 編碼,然后在 php 中使用 JSON 解碼,請參閱此問題Pass Javascript Array -> PHP

暫無
暫無

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

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