Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用AJAX将数组传递到PHP文件_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript 使用AJAX将数组传递到PHP文件

Javascript 使用AJAX将数组传递到PHP文件,javascript,jquery,ajax,Javascript,Jquery,Ajax,我应该用AJAX向PHP文件传递一个数组和一个变量 如果我尝试只传递变量,一切正常,但是如果我尝试同时传递数组或仅传递数组,我会遇到一些问题 这是我的密码: function myfunction() { var someObj={}; someObj.SpecificGranted=[]; xmlHttp.open('POST', "file.php", true); xmlHttp.onreadystatechange = function

我应该用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);
  }
}
函数myfunction()
{  
var someObj={};
someObj.specific=[];
open('POST','file.php',true);
xmlHttp.onreadystatechange=函数()
{
if(xmlHttp.readyState==4)
{ 
if(xmlHttp.status==200)
{
数据:{
myvar:,
myarray:someObj.specific;
}            
}
}
};
setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
xmlHttp.send(“myvar=“+myarray”);
}
}
我还想问如何检索PHP文件中的数组。。。因为
我不确定
$\u POST['myarray']
是正确的方法。

您可以尝试两件事:一件是
json字符串化
数组变量,然后在php中执行
json\u解码
,以获取数组

myarray: JSON.stringify(someObj.SpecificGranted);
或者,如果它是一个简单的数组,您可以通过

myarray[]: someObj.SpecificGranted;
请注意myarray中的
[]。您可以在php中使用
$\u POST['myarray[]]

试试这个(在
jQuery
中):

我试着发出警报(“你好”);在数据{…}之后。如果内部数据中没有myarray[]:someObj.SpecificPermited;但如果我添加它,则不会显示警报。
function myfunction() {
    var someObj = {};
    someObj.SpecificGranted = ['one', 'two'];
    $.get('file.php', {myvar: '123', myarray: someObj.SpecificGranted}, function(data) {
        console.log(data);
    });
}
myfunction();