【问题标题】:How to covert javascript array to php array and load it in a div如何将javascript数组转换为php数组并将其加载到div中
【发布时间】:2015-03-06 11:01:07
【问题描述】:

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

我已经在 Internet 上搜索了一个解决方案,但我无法在这个示例中真正使用它。我也是 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;
    }
?>

【问题讨论】:

  • true 作为第二个参数添加到json_decode() 函数。如果您仍然不确定它的结构,请使用print_r()var_dump()

标签: javascript php ajax


【解决方案1】:

好的,这是将数据插入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;
    }
?>

我自己没有测试过。

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多