简体   繁体   中英

How to post an array of objects in JSON with Ajax Post to PHP?

I can successfully post an array to PHP using Ajax Post but I want to extend this functionality to post an array of objects instead an array of values..im struggling to find clear examples of how to do this.

Here is how I am posting the array of values from the jQuery/Javascript client script:

var placesfortrip = {};
placesfortrip["place"+counter] = inputVal;

//note counter is an int that gets incremented for each value
//inputVal is a string with the new value to be added 

 var inputVal = jQuery("#edit-location").val();  
          jQuery.ajax({
            url: "/createtrips/updateitin",
            type: 'POST',
            data: placesfortrip,
            dataType: 'json'
            });

Then at the PHP side I read the data like this:

 $citynames = array();

    foreach ($_POST as $key=>$value) {

    $citynames[$key]= $value;

    }

How can I modify the above to post an array of objects instead of values? Im particularly confused as to how to read the array of objects from the PHP side.

You can try this code to send your data to php file

 var status  = document.getElementsByName("status")[0];
    var jsonObj = []; //declare array

    for (var i = 0; i < status.options.length; i++) {
        jsonObj.push({id: status.options[i].text, optionValue: status.options[i].value});
    }

then replace this line

data: placesfortrip,

with

data: jsonObj,

for other help you can also help this one

Most of the popular JavaScript frameworks have JSON utility functions included. For instance, jQuery has a function that directly calls a url and loads the JSON result as an object : http://docs.jquery.com/Getjson

However, you can get an open-source JSON parser and stringifier from the json website :

https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Then, simply include the code and use the JSON.stringify() method on your array.

You could also just forget json and post the array as it is. Eg in JavaScript:

var slideShowImages = new Array();
var image = {};
image['id'] = 1;
image['title'] = "Title 1";
slideShowImages[0] = image;

etc. filling in the whole array in javascript. Then the Ajax call as:

$.ajax({
  type : 'POST',
  url: BASE_REQUEST_URL + 'apiModule/performAddEditSlideShow',
  cache: false,
  data: {
    images: slideShowImages
  }
});

Then in PHP, simply loop through it:

$images = $_POST['images'];
foreach($images as $image) {
  $title = $image['title'];
}

您应该能够将对象发布到服务器,并使用json_decode($ _ POST ['some_key“])将该对象用作服务器上的数组/对象

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