繁体   English   中英

如何将javascript数组转换为php数组并将其加载到div中

[英]How to covert javascript array to php array and load it in a div

我的问题:我不知道如何抓住我的javascript数组(var数组)并将其转换为php数组.php数组也应该能够以某种方式获取值。

我在互联网上搜索了一个解决方案,但我不能真正让它在这个例子中工作。 我也是Ajax的新手,可能有些事情我做得不对。 任何帮助和解释将非常感激。

script.php的

这个文件应该在结果div中加载php数组。

<div class="test" style="width: 200px height: 50px; background-color: #000;">test</div>
<div class="result" style="width: 200px height: 50px; background-color: yellow; color: #FFF;"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
var array = new Array("test", "test");

$(".test").click(function () {
alert('pressed');
array.push("test");
alert(array);
dataString = array; 
    var jsonString = JSON.stringify(dataString);
    $.ajax({
        type: "POST",
        url: "php.php",
        data: {data:dataString}, 
        cache: false,
        success: function(){
            alert("OK");
        }
    });
  });
});
</script>

php.php

应该将javascript数组作为php数组回显

<?php
    $data = json_decode(stripslashes($_POST['data']));

    foreach($data as $d){
        echo $d;
    }
?>

好的,这是将数据插入div的ajax调用部分:


    $.ajax({
        type: "POST",
        url: "php.php",
        data: {data:dataString}, 
        cache: false,
        success: function(data){
            $('.element_class').html(data);
        }
    });

这是PHP部分:

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

    foreach($data as $d){
        echo $d;
    }
?>

我自己没有测试过这个。

暂无
暂无

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

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