简体   繁体   English

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

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

My problem: I'm not sure how to grab my javascript array (var array) and convert it to a php array.The php array also should be able to grab the values somehow. 我的问题:我不知道如何抓住我的javascript数组(var数组)并将其转换为php数组.php数组也应该能够以某种方式获取值。

I've searched for a solution on the internet but I can't really get it to work in this example. 我在互联网上搜索了一个解决方案,但我不能真正让它在这个例子中工作。 I'm also new to Ajax and there are probably some things i'm not doing right. 我也是Ajax的新手,可能有些事情我做得不对。 Any help and explanation would be really appreciated. 任何帮助和解释将非常感激。

Script.php script.php的

This file should load the php array in result div. 这个文件应该在结果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 php.php

Should echo the javascript array as a php array 应该将javascript数组作为php数组回显

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

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

OK, this is the ajax call part to insert the data into a div: 好的,这是将数据插入div的ajax调用部分:


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

This is the PHP part: 这是PHP部分:

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

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

I havn't tested this myself. 我自己没有测试过这个。

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

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