English 中文(简体)
jQuery ajax请求发送多个数组并在php脚本中访问它们的值
原标题:jQuery ajax request sending multiple arrays and accessing their values in php script

I am trying to pass multiple arrays to my script and from there I will insert these array values in database. In Branches_Control.php I want to save these array values in PHP variables and then pass them to my model and loop through that PHP array variable to insert them in the DB.

这是我的AJAX请求:

var finalplaces = [];
var finallongArr = [];
var finallatArr = [];
var finalphone = [];
var finalcompanyName = [];

for (var i = 0; i < places.length; i++) {
    if (finalplaces[i] != null) {
        finalplaces[i].push(places[i])
        finallongArr[i].push(longitudeArr[i]);
        finallatArr[i].push(latitudeArr[i]);    
        finalphone[i].push(phone[i]);
        finalcompanyName[i].push(companyName[i]);
    }
}

$.ajax({
    type:  POST ,
    url: "Branches_Control.php",
    data: "Places=" + finalplaces +
            "&longitudeArr=" + finallongArr +
            "&latitudeArr=" + finallatArr +
            "&phones=" + finalphone +
            "&companyNames=" + finalcompanyName,
    success: function(data) {
        alert(data + "Succese");
        document.getElementById("asd").innerHTML = data;
    }
});

我试图在分支机构中执行的操作_Control.php

$places = $_POST[ Places ];
echo $places[0];

有人能告诉我为什么这不起作用吗?

最佳回答

在您的代码中:

var finalplaces = [];
for (var i = 0; i < places.length; i++) {
    if (finalplaces[i] != null) {
        finalplaces[i].push(places[i])
    }
}

条件if(finalplaces[i]!=null)不能是true,因为数组是空的,所以永远不会填充数组
我想您想反转测试:if(finalplaces[I]==null)

问题回答

您的错误在这里:

   data: "Places=" + finalplaces +
            "&longitudeArr=" + finallongArr +
            "&latitudeArr=" + finallatArr +
            "&phones=" + finalphone +
            "&companyNames=" + finalcompanyName,

如果您以字符串形式发送数据,则必须使用以下字符串对这些数组进行字符串化,例如:

"&longitudeArr=" +JSON.stringify(finallongArr )

然后在服务器端,您必须进行json解码:

 $longitudeArr= json_decode($_POST[ longitudeArr ])

或者更简单地说,使用jquery功能,您可以将数据作为对象进行传递,具体操作如下:

data:{longitudeArr:finallongArr ,  latitudeArr: finallatArr , phones: finalphone .....}

最后一种方法的优点是,在php站点上,您可以立即获得数组:

$longitudeArr= $_POST[ longitudeArr ] //this is an array

尝试





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签