简体   繁体   English

AJAX-Javascript数组到php

[英]AJAX - Javascript array to php

I know that there are so many to find on the internet, however, I have been trying this for hours now, and still not working, Maybe the community could help me out:) 我知道在互联网上可以找到很多东西,但是,我已经尝试了好几个小时了,但仍然无法正常工作,也许社区可以帮助我:)

http://jsfiddle.net/dkk2nqyg/14/ http://jsfiddle.net/dkk2nqyg/14/

I've got a little explanation in the jsfiddle, else, you can take a look in my previous question, JavaScript array splice 我在jsfiddle中有一些解释,否则,您可以看一下我之前的问题JavaScript数组拼接

Basicly, I want the values from selected ( 3 picked up cards ) in php, because I want to mail those values;) 基本上,我想要从php中selected的值(3张拾取的卡)中,因为我要邮寄这些值;)

 $.ajax({
   url: 'data.php',  //I actually want it to be on same page, trying this for debugging
   type: 'post',
   data: {data : selected},
   success: function(data) {
        alert("worked");
   }
});

in the data.php : 在data.php中:

<?php
$data = json_decode(stripslashes($_POST['data']));
  foreach($data as $d){
     echo $d;
  }
?>

I would like that I don't even need that data.php but just 1 page, so in the index.php, is that even possible? 我想我什至不需要那个data.php,而只需要一页,所以在index.php中,这甚至可能吗?

Edit: Please, link a JsFiddle, would really help! 编辑:请链接JsFiddle,将真的有帮助!

First the ajax request should be within the click handler 首先,ajax请求应在点击处理程序中

$('#mail').click(function () {
    console.log($('#dvDest .flipper').get())
    var selected = $('#dvDest .flipper').map(function () {
        return $(this).data('src')
    }).get();
    alert(selected)
    $.ajax({
        url: 'data.php', //I actually want it to be on same page, trying this for debugging
        type: 'post',
        data: {
            data: selected
        },
        success: function (data) {
            alert("worked");
        }
    });
})

then in server side loop through the array like (Not sure about the PHP syntax) 然后在服务器端像这样遍历数组(不确定PHP语法)

<?php
  foreach($_POST['data'] as $d){
     echo $d;
  }
?>

you can write a condition as if request object have post values then 您可以编写条件,就像请求对象具有发布值,然后

$data = json_decode(stripslashes($_POST['data']));
 foreach($data as $d){
  echo $d;
}

else your homepage display code 否则您的首页显示代码

So,index.php is enough 因此,index.php就足够了

For using a single page, eg: index.php 对于使用单个页面,例如:index.php

at the top of index.php you do: 在index.php的顶部,您可以执行以下操作:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Your code goes here
    exit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM