Javascript POST无法正常工作 - 将Javascript数组发送到PHP

时间:2013-04-24 00:14:50

标签: php jquery ajax post

我知道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不正确的问题吗?

感谢。

4 个答案:

答案 0 :(得分:2)

你对ajax如何运作有误解。虽然jquery让它变得简单,但它仍然不是自动的。你应该找到一个关于jjery的ajax的教程,但如果你只是想发送一个数组到php并在屏幕上看到输出,这样的东西就可以了:

的index.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>

catcher.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调用。发送数组的工作方式相同,只需用发送数组替换获取文本框值即可。

答案 1 :(得分:0)

这是打开页面时发生的情况(index.php

  1. GET发出index.php请求,并返回内容。 $_POST数组中有值,因此您的print_r()行无效。
  2. 执行Javascript,通过AJAX向POST发送index.php请求。请注意,这是一个全新的请求,与原始GET分开。 {em>此请求将填充$_POST数组,但会丢弃该响应。
  3. 希望这能说明你可以做什么。

    ajax.php

    <?php echo json_encode($_POST);
    

    的index.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>
    

答案 2 :(得分:0)

不是将变量toSearchArray声明为数组。认为它是一个javascript对象。 var toSearchArray = {}。

答案 3 :(得分:-1)

嗯,我不认为在数组方面做到这一点是正确的,看你需要在javascript中使用JSON编码然后在php中使用JSON解码 请参阅此问题Pass Javascript Array -> PHP