将带有AJAX的数组传递到PHP文件

Passing Array with AJAX to PHP file

本文关键字:PHP 文件 数组 AJAX      更新时间:2023-09-26

我应该用AJAX向PHP文件传递一个数组和一个变量。

如果我试图只传递变量,一切都很好,但如果我试图同时传递数组或只传递数组,我会遇到一些问题。

这是我的代码:

function myfunction()
 {  
     var someObj={};
     someObj.SpecificGranted=[];
    xmlHttp.open('POST', "file.php", true);    
    xmlHttp.onreadystatechange = function() 
    {
        if(xmlHttp.readyState == 4) 
        { 
            if (xmlHttp.status == 200) 
            {
            data: {
                    myvar : <?php echo $myvar;?>,
                    myarray:someObj.SpecificGranted;
                }            
             }
        }
    };
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    xmlHttp.send("myvar=<?php echo $myvar;?>"+myarray);
  }
}

我还会问如何在PHP文件中检索数组。。。因为我不确定$_POST['myarray']是否正确。

您可以尝试两件事,一件是json stringify数组变量,另一件是在php中执行json_decode以取回数组。

myarray: JSON.stringify(someObj.SpecificGranted);

或者,如果它是一个简单的数组,您可以通过直接将其发送到php

myarray[]: someObj.SpecificGranted;

注意[] in myarray。您可以使用$_POST['myarray[]']在php中获取它。

试试这个(在jQuery中):

function myfunction() {
    var someObj = {};
    someObj.SpecificGranted = ['one', 'two'];
    $.get('file.php', {myvar: '123', myarray: someObj.SpecificGranted}, function(data) {
        console.log(data);
    });
}
myfunction();