使用 ajax 将 javascript 数组从 file.xhtml 传递给 php 数组

Pass javascript array from file.xhtml to php array using ajax

本文关键字:数组 php xhtml ajax javascript 使用 file      更新时间:2023-09-26

我有 2 页是file.xhtmlsubmit-exec.php的。我正在使用ajax将我的javascript数组从xhtml文件传递到php。我在网上找到了几个教程,但没有一个能解决我的问题。我仍然想知道 xhtml 是否有任何问题?

数组:

var array = [];
array.push({ name: "name", value: document.forms["form"]["name"].value});
array.push({ name: "email", value: document.forms["form"]["email"].value});
array.push({ name: "mobile", value: document.forms["form"]["mobile"].value});

文件.xhtml

$.ajax({ //to run exec in background
    type: 'POST',
    url: 'submit-exec.php',
    data: {'data' : array},
    success: function(){
        alert("ok");
    }
});

提交执行.php

$myArray = $_POST['data'];
print_r($myArray);

有人可以帮助我吗?

谢谢!

你可以简单地发送一个对象(我不更改变量名称"array"以适应你的ajax,但你肯定应该)

var array = {name: document.forms["form"]["name"].value, email: document.forms["form"]["email"].value, mobile: document.forms["form"]["mobile"].value}  

无需转换为字符串

对象无法通过 POST 发送。因此,为了使您的代码正常工作,您必须将数组转换为字符串并将其转换回服务器端的数组。例如:

data: {'data' : array.join(',')},

在服务器端,使用 explode 将其转换回数组:

$myArray = explode(",", $_POST['data']);