简体   繁体   English

通过JSON对象发送时如何捕获Ajax页面中的数组

[英]how to capture array in ajax page when sent through JSON object

i am sending an array from one page to another through ajax.i used JSON object for this purpose.I am able to send but i am not able to capture in the ajax page.Please help me how to capture the array values. 我通过ajax将一个数组从一个页面发送到另一页面。我为此目的使用了JSON对象。我能够发送但无法在ajax页面中捕获。请帮助我如何捕获数组值。 javascript: JavaScript的:

var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "ajaxpage.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(response){
            alert("ok");
           $('#test').html(response);
        }
    });

PHP page: PHP页面:

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

  // here i would like use foreach:

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

please help me in this regard. 请在这方面帮助我。 I am stuck up here 我被困在这里

If you want to decode the JSON into an associative array, you should specify that in json_decode : 如果要将JSON解码为关联数组,则应在json_decode指定:

Replace 更换

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

With

$data = json_decode(stripslashes($_POST['data']), true);

See json_decode reference for more information 有关更多信息,请参见json_decode参考


Also, is dataString possibly already a JSON string? 另外, dataString可能已经是JSON字符串了吗?

I think this is what you want, I have tried and it works 我想这就是您想要的,我已经尝试过并且有效
in your php: 在您的php中:

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

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

in your jsvascript/jquery: 在您的jsvascript / jquery中:

<script>
$(document).ready(function(){
    $('a').on('click',function(){
    var dataString = {
        'id':'1',
        'name':'peter parker',
        'age':'unknown',
        'role':'spiderman'
    }
    $.ajax({
         url: "<?php echo $this->webroot;?>test_1.php",
         data: {'data':dataString}, 
         type: "POST",
         cache: false,
         success: function(response){
         alert("ok");
         $('#test').html(response);
        }
     });
   })
})
</script>

in your html 在你的HTML

<a href="javascript:void(0);">Click Me</a>
<div id="test"></div>

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

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