简体   繁体   中英

Posting and parsing data sent from JQuery to PHP

I'm trying to use JQuery to pass a data structure that looks similar to the one below to a php script:

{
  "shopping":
    [
      {
         "type": "online",
         "mood": 9 
      },
      {
         "type": "mood",
         "mood": 4
      }
    ],
   "researching":
     [
      {
         "type": "online",
         "mood": 3 
      },
      {
         "type": "library",
         "mood": 1
      }
     ]
}

This data in the JSON changes based on forms and sliders a user manipulates, and then the JSON is sent asynchrounously with a submit button. I am having trouble figuring out how to use JQuery to submit this request, and how to have PHP parse it. I would like to send this data using the POST method. Right now, I'm using:

$.post('server/dataInput.php',submissions, function(data){
    console.log(data);
});     

Where submissions is the JSON object, however this doesn't seem to be working. I also dont' know how I would then parse this JSON on PHP's end.

If you are using jquery 1.4.0+ json_decode is not necessary. Your data will be received in PHP as an array.

Example:

JS fragment:

var testData = {
    "shopping": [
      {
         "type": "online",
         "mood": 9 
      },
      {
         "type": "mood",
         "mood": 4
      }
    ],
    "researching": [
      {
         "type": "online",
         "mood": 3 
      },
      {
         "type": "library",
         "mood": 1
      }
    ]
};

function sendTest() {
    $.post('test.php', testData, function(data) { console.log(data); });
}

Call sendTest ...

test.php:

<?php

var_dump($_POST);

And your success function will display what test.php outputted:

array(2)
{
  ["shopping"]=> array(2)
  {
    [0]=> array(2)
    {
      ["type"]=> string(6) "online"
      ["mood"]=> string(1) "9"
    }
    [1]=> array(2)
    {
      ["type"]=> string(4) "mood"
      ["mood"]=> string(1) "4"
    }
  }

  ["researching"]=> array(2)
  {
    [0]=> array(2)
    {
      ["type"]=> string(6) "online"
      ["mood"]=> string(1) "3"
    }
    [1]=> array(2)
    {
      ["type"]=> string(7) "library"
      ["mood"]=> string(1) "1"
    }
  }
}

So, everything works out-of-the-box! :)

您应该使用PHP json_decode解压缩JSON数据吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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