当前位置: 动力学知识库 > 问答 > 编程问答 >

Cannot pass array to PHP script using Ajax

问题描述:

I'm having a weird problem here and I can't seem to figure out why I can't pass one array to the PHP script using ajax, but I can pass another array without any problems.

Here's my ajax function:

function update(){

var hr = new XMLHttpRequest();

var url = "update.php";

var vars = "array="+arr;

hr.open("POST", url, true);

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.send(vars);

}

The variable "arr" is a 2d array loaded with coordinates, like so: [[2,3],[4,5],[5,2]...] and it's user-generated, every time user inserts new set of coordinates, I use PUSH to add them to the array.

It is declared just above this function, inside the javascript.

This seems to be working fine, because when I do alert(JSON.stringify(arr)); inside the ajax function, I can see clearly the coordinate pairs pop up in my browser.

However, when I catch the array on the other side (php script) and write it into a notepad file using:

<?php

$fp=fopen("ajax.txt","w");

$data = $_POST['array'];

fwrite($fp,$data);

fclose($fp);

?>

The file ajax.txt is created but remains empty.

However, when I initialize another array (arr1) inside the ajax function, like this:

function update(){

var arr1=[[2,3],[4,5],[5,7]];

var hr = new XMLHttpRequest();

var url = "update.php";

var vars = "array="+arr1;

hr.open("POST", url, true);

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.send(vars);

}

The PHP script seems to write the array to the notepad file without any problems! Why does this happen? Clearly the "arr" variable is not empty, because we can see the contents of it using alert.

Any ideas?

分享给朋友:
您可能感兴趣的文章:
随机阅读: