javascript - 如何使用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";
}
})
}
解决方案
您必须发送值而不是对象。JavaScript 对象不能存在于 JavaScript 之外,因此数组(它们也是对象,或者更确切地说是所有对象的构造函数(OOP 中的母类或父类)的函数)或至少将它们转换为 PHP 可以读取以转换的字符串一个 PHP 对象。AJAX 是为了更早地使用 XML,您可以将其用作文字(意思是字符串)的 JSON,并且可以用作元数据。您可以通过 Objects paar key/value 上的循环或(第二种方式)使用 .toString() 来执行第一种方法,而对于第三种想法,您必须创建一个临时的 .json 文件(或 XML,如果您愿意)。另一种方法是创建一个 HTML 表单并使用它(强制在代码中提交),因此您将直接在 PHP 中获取 POST/GET 全局值。
推荐阅读
- swift - 如果鼠标移动太快,SwiftUI onHover 不会注册鼠标离开元素
- r - 无法使用 {sdmData} 编译数据集 - 错误
- elixir - Elixir HTTP close connection error with Hackney {error: :closed}
- gradle - 在intellij中执行spring boot项目失败,在终端中工作
- excel - Excel如何创建引用并列出名称?
- c# - 闪烁文本如果复选框被选中为真
- javascript - 如何在Javascript中更新特定数组元素索引位置和对象属性的特定数组?
- javascript - 具有功能的电子上下文菜单 BuildFromTemplate
- javascript - 我无法在 node.js 和 oracle 之间连接
- dynamics-crm - 使用 DynamicsCRM 2016 中的工作流更新营销列表中的所有联系人