使用AJAX发送数据并使用PHP接收

时间:2013-08-19 10:40:15

标签: php jquery json each

我有一个生成JSON数组的脚本,基于用户选择的值。这些值作为带有AJAX的JSON发送到PHP脚本,该脚本应接收此值并对其进行处理。

可能出现什么问题?

JSON(已发送):

[{
  "Pages":
         {"name":" Page Name 1",
          "id":"252456436636644"}
         },
  {
   "Pages":{
          "name":" Page Name 2",
          "id":"345345435435232"
          }
}]

Jquery的:

var json_pages = JSON.stringify(publish);

$.ajax({
    url: "post.php",
    type: "post",
    data: { PublishToPages: json_pages },
    success: function(){},
    error: function(){}   
}); 

问题是我从PHP收到的JSON没有获取数据,

if($_POST['PublishToPages']) {

    $json = $_POST['PublishToPages'];

    $array = json_decode($json, true);

    foreach($array as $item) { 
        $page_id = $item['Pages']['id'];
        echo $page_id;  
    }
}

如果我在PHP脚本中手动输入JSON,就像它一样工作,

if ($_POST['PublishToPages']) {

    $json = '[{"Pages":{"name":" Page Name","id":"234545355345435"}},{"Pages":{"name":" Page Name 2","id":"345345435435435435"}}]';

    $array = json_decode($json, true);

    foreach($array as $item) { 
    $page_id = $item['Pages']['id'];
        echo $page_id;  
    }
}

3 个答案:

答案 0 :(得分:0)

尝试使用:

if($_POST['PublishToPages']) {

    $json = $_POST['PublishToPages'];
    $items = array();

    $array = json_decode($json, true);

    foreach($array as $item) { 
        $page_id = $item['Pages']['id'];
        $items[] = $page_id;  
    }

    echo json_encode($items);
}

答案 1 :(得分:0)

试试这个

$.ajax({
    url: "post.php",
    type: "post",
    dataType:"json",
    data: { PublishToPages: json_pages },
    success: function(){},
    error: function(){}   
});  

答案 2 :(得分:0)

感谢所有输入!我用var_dump想出来并意识到它是编码错误所以添加了stripslashes();它工作了! :)

if ($_POST['PublishToPages']) {

    $json = stripslashes($_POST['PublishToPages']);

    $array = json_decode($json, true);

    foreach($array as $item) { 
        $page_id = $item['Pages']['id'];
        echo $page_id;  
    }
}