不要从ajax调用传递的php页面上检索对象

时间:2019-05-15 22:10:23

标签: php json ajax

嗨,我没有将Ajax数据检索到PhP页面,并抛出了错误。我将数据作为json对象传递。 我得到的错误是

enter image description here

Edit.php

$('#regForm').on('submit', function (e) {
var url = document.URL;                // Get current url

var id = url.substring(url.lastIndexOf('=') + 1);

var data1 = $("#regForm").serialize();

data = {data:data1,id:id};

console.log(data)
$.ajax({
    method:"POST",
    url: 'update.php',
    dataType : 'json',
    data: data,
    success: function () {
      alert('form was submitted');
    }
  });

});

update.php

if(isset($_POST["submit"]))  
{  

  print_r($_POST['data']);

  // Error::: Undefined index:data in

2 个答案:

答案 0 :(得分:0)

阅读我的评论,然后看一下:

JavaScript可能如下所示

$('#regForm').on('submit', function(e){
  var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
  if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
    var serialData = $(this).serialize()+'&'+serialId;
    $.ajax({
      method:'POST', url:'update.php', dataType:'json', data:serialData},
      success:function(jsonObj){
        console.log(jsonObj);
      }
    });
  }
  e.preventDefault();
});

PHP可能看起来像这样

<?php
if($_POST['id']){
  // each property as $_POST[propertyHere]
  // sending back to JavaScript
  $c = new stdClass; $c->someProp = 'some value';
  echo json_encode($c); // dataType is json so you should get Object as result
}
?>

答案 1 :(得分:0)

使用隐藏的输入字段传递ID,然后将数据序列化,然后可以按名称在php页面上使用。 $ _POST ['name'];

相关问题