weixin_33747129 2016-11-03 22:21 采纳率: 0%
浏览 34

在PHP中使用Javascript数组

I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.

Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.

Now I want to pass that JS array to PHP, so I can create tables with it.

Here's what I have done.

$(".Go").click(function() {
    var enc = JSON.stringify(tableChoice);
    $.ajax({
        method: 'POST',
        url: 'calc.php',
        data: {
            elements: enc
        },
        success: function(data) {
            console.log(enc);
        }
    });
});

And in my calc.php I got this to get the values to PHP.

<?php
    $data = json_decode($_POST['elements'],true);
    echo $data;
?>

Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:

Undefined index: elements

I am sure I am looking at this the wrong way, interpreting it wrong. Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.

  • 写回答

2条回答 默认 最新

  • weixin_33720956 2016-11-03 22:31
    关注

    With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.

    You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.

    So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?

    评论

报告相同问题?