从php文件访问javascript数组


access javascript array from a php file

如何将javascript数组vArray传递给File.php,并从vArray中检索这两个值。

我试过了:

<input type="button" id="button" onClick = "send_V();" >
<script>
// Creat Array with Values from checkboxes
$('input[type=checkbox]:checked').each(function() {
    vArray.push($(this).val());
});
// Set array to only 2 values ( disable checkboxes)
var n = $('input[type=checkbox]:checked').length >= 2;  
$('input[type=checkbox]').not(':checked').attr('disabled',n);
// Send array to File.php where I can manipulate its value1, and value2 to query db
function send_V(vArray)
{
    $.ajax({
        type: "POST",
        url: "File.php", 
        beforeSend: function () {
            $("#result").html("<option>Loading ...</option>");
        },
        data: "vArray="+vArray,
        success: function(msg){
            $("#result").html(msg);
        }
    });
} 
</script>

在php端(File.php)

$value = $_POST['vArray'];
var_dump(vArray);

但我不知道如何操作javascript变量。有人能给我看一个简单有效的方法吗?这个逻辑有什么错?感谢

使用json。用js编码数组(如何将javascript对象编码为JSON?),用php解码(http://php.net/manual/ro/function.json-decode.php)。

如果使用"data"参数的对象设置ajax调用:

$.ajax({
   type: "POST",
   url: "File.php", 
   beforeSend: function () {
     $("#result").html("<option>Loading ...</option>");
   },
   data: { vArray: vArray },  // here
   success: function(msg){
     $("#result").html(msg);
   }
 });

然后jQuery将创建如下的HTTP请求参数:

 vArray[]=first value
 vArray[]=second value

等等。在服务器端,当您访问时

 $vArray = $_POST['vArray'];

你会拿回阵列的。换句话说,如果您不想的话,您不必显式地使用JSON。

用于现代浏览器的纯javascript(需要支持formData和xhr2)(chrome、safari、ios、android、ie10)

js

var vArray=['a','b','c'],
json=JSON.stringify(vArray);//this converts the array to a json string
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
 c=new XMLHttpRequest;
 c.open(e||'get',a);
 c.onload=b;
 c.send(d||null)
}
function whatever(){
 console.log('json posted',this.response)
}
ajax('page.php',whatever,'post',{'json':json});

page.php

<?php
print_r(json_decode($_POST['json']));//converts the json string to a php array
?>

另一个解决方案是张贴整个表单

html

<form>
<input name="a" value="x">
<input type="radio" name="b" value="x">
//and many other input & text fields
</form>

js

function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
 c=new XMLHttpRequest;
 c.open(e||'get',a);
 c.onload=b;
 c.send(d||null)
}
function whatever(){
 console.log('form posted',this.response)
}
var form=document.getElementsByTagName('form')[0],
    fd=new FormData(form);
ajax('page.php',whatever,'post',fd);

php

<?php
print_r($_POST);
?>

xhr2

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

formData

https://developer.mozilla.org/en-US/docs/Web/API/FormData

我尝试了以下似乎很好的方法:

<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>

它对我来说运行得很好。代码取自http://www.developphp.com/view.php?tid=1185

@Pointy和@Cocco的回答可能是正确的,我无法用Jquery正确实现它,也不想使用Form。希望这能帮助