繁体   English   中英

如何使用Ajax Post将JSON中的对象数组发布到PHP?

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

我可以使用Ajax Post成功地将数组发布到PHP,但是我想扩展此功能以发布对象数组而不是值数组..im努力寻找方法的清晰示例。

这是我从jQuery / Javascript客户端脚本中发布值数组的方式:

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'
            });

然后在PHP端读取如下数据:

 $citynames = array();

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

    $citynames[$key]= $value;

    }

如何修改以上内容以发布对象数组而不是值? 我对于如何从PHP端读取对象数组特别困惑。

您可以尝试使用此代码将数据发送到php文件

 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});
    }

然后替换这行

data: placesfortrip,

data: jsonObj,

对于其他帮助,您也可以帮助这一

大多数流行的JavaScript框架都包含JSON实用程序功能。 例如,jQuery具有直接调用url并将JSON结果作为对象加载的函数: http : //docs.jquery.com/Getjson

但是,您可以从json网站获取开源JSON解析器和字符串化器:

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

然后,只需添加代码并在数组上使用JSON.stringify()方法即可。

您也可以忘记json并按原样发布数组。 例如JavaScript:

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

等在javascript中填写整个数组。 然后,Ajax调用为:

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

然后在PHP中,只需遍历它:

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

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

暂无
暂无

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

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