首页 > 解决方案 > 如何使用ajax将多个点发送到php文件

问题描述

我正在尝试发送用户创建的一些点,但我不知道是否将其作为对象或数组发送

我试图像对象一样发送它,它只发送[对象对象]。

这是创建点的函数

function onSvgClick(event) {
  const customSvg = document.getElementById('my-svg');
  const svgInfo = 'http://www.w3.org/2000/svg';

  const circle = document.createElementNS(svgInfo, 'circle');
  circle.setAttribute('cx', event.offsetX);
  circle.setAttribute('cy', event.offsetY);
  circle.setAttribute('stroke', 'red');
  circle.setAttribute('stroke-width', 5);
  circle.setAttribute('r', 5);
  circle.setAttribute('fill', 'green');
  circle.setAttribute('fill-opacity',0);
  circle.setAttribute('id',currentid);

  points[currentid] = {id: currentid, x: event.offsetX, y: event.offsetY};

  alert(points[currentid]);
  currentid++;
  customSvg.appendChild(circle);

  circle.addEventListener('contextmenu', function(event) {
    circle.remove(circle.id);
    event.preventDefault();
  });
}

这是我的ajax

var nah = JSON.stringify(points);
function onBtnClick(event){
      alert(point);
      $.ajax( {
        url:"../php/points.php",
        method:'POST',
        data:{ body:nah},
        success: function(response){
            window.location = "../php/points.php";
        }

    })

    }

标签: javascriptphpjqueryajax

解决方案


您必须发送值而不是对象。JavaScript 对象不能存在于 JavaScript 之外,因此数组(它们也是对象,或者更确切地说是所有对象的构造函数(OOP 中的母类或父类)的函数)或至少将它们转换为 PHP 可以读取以转换的字符串一个 PHP 对象。AJAX 是为了更早地使用 XML,您可以将其用作文字(意思是字符串)的 JSON,并且可以用作元数据。您可以通过 Objects paar key/value 上的循环或(第二种方式)使用 .toString() 来执行第一种方法,而对于第三种想法,您必须创建一个临时的 .json 文件(或 XML,如果您愿意)。另一种方法是创建一个 HTML 表单并使用它(强制在代码中提交),因此您将直接在 PHP 中获取 POST/GET 全局值。


推荐阅读