AJAX不向PHP发送数据

时间:2013-12-23 03:12:25

标签: php ajax send

在此脚本中,数据将被发送,但不会发送更新的变量值。硬编码数据按预期发送。我该如何解决这个问题或绕过它呢?

    username = '';  // supposedly these variables are global
    tree_name = ''; // I also tried plugging in- $('#username').data("username") -directly.. same results.

    $(function() {
        username = $('#username').data("username");    // updating value
        tree_name = $('#tree_name').data("tree_name"); // idem....
    });


    var options = {
        type: "POST",
        url: "/decision/p_tree2/",

        data: {
            username: username,     // this should send the data
            tree_name: tree_nam     // ...
        },

    success: function(response) {
    console.log(response);      
    }
};

$("form").ajaxForm(options);

PHP:

public function p_tree2 (){
    $data = Array();
    $data['username'] = $_POST['username'];
    $data['tree_name'] = $_POST['tree_name'];

    echo print_r($data);    // result: both $data['username'] and $data['tree_name'] equal ""

}

1 个答案:

答案 0 :(得分:1)

重新格式化您的代码,如下所示。还要更正数据中tree_name中的拼写错误。您使用了tree_nam

$(function() {
    var username, tree_name,options;

    username = $('#username').data("username");
    tree_name = $('#tree_name').data("tree_name");

    console.log(username); //make sure
    console.log(tree_name); // console outputs what you need to pass 

    options = {
        type: "POST",
        url: "/decision/p_tree2/",

        data: {
            username: username,     // this should send the data
            tree_name: tree_name     // ***correct this typo***
        },

        success: function(response) {
            console.log(response);
        }
    };

    $("form").ajaxForm(options);
});