PHP无法读取阵列通过AJAX发送 [英] PHP Can't Read Array Sent by AJAX

查看:137
本文介绍了PHP无法读取阵列通过AJAX发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  从PHP发送的数据阵列的JavaScript

我要送与阿贾克斯数组到PHP文件。阵列是应存储在数据库中的名称的列表。为了doublecheck这一点,我想呼应的PHP文件中的 sql_query 创建。但反应总是

I'm sending an Array with ajax to a php file. The Array is a list of names which should be stored in a database. In order to doublecheck this, I tried to echo the sql_query created in the php file. But the response is always

有关的foreach()提供的参数无效...

Invalid argument supplied for foreach()...

所以,我搜索所以对于一些解决方案,并经常得到的答案是什么你的'阵'是不是数组。所以,我赞同提交给PHP,返回在一行上全部通过名称的阵列(我认为意味着数组中的PHP文件到达)。

So I searched SO for some solutions, and often the answer was something like "your 'Array' is not an Array". So I echoed the Array submitted to the php, which returns all passed names on one line (what I think means that the Array arrives in the php-file).

因此​​,这里是我的JS ......

So here's my JS...

var tourneyData = {
    tName : tourneyName,
    tNum : number,
    tNames : names, // this is an array
    tInt : international,
    tLig : liga,
    tStars : stars
};

$.ajax({
    type: "POST",
    url: "php/storeTourney.php",
    data: tourneyData,
    datatype: "json",
    success: function(response){
        alert("response " + response);
    }
});

...和PHP code

... and PHP code

$tName = $_POST['tName'];
$tNum = $_POST['tNum'];
$tNames = $_POST['tNames'];
$tInt = $_POST['tInt'];
$tLig = $_POST['tLig'];

$insert = "";
foreach($tNames as $d){ // line pointed in the error message
    $insert += "INSERT INTO NAMES VALUES('test', '".$d."');";
}

echo $insert;

我完全不明白什么是错的,在code。怎么可能是错误的的foreach()语句来,如果 $ tNames 显然是一个数组?

I do not exactly understand what's wrong in the code. What could possibly be wrong in the foreach()-statement, if $tNames obviously is an Array?

推荐答案

您需要提示你希望得到您的数据作为数组的PHP。命名tNames为 tNames []

You need to hint to php that you want to get your data as an array. name tNames as tNames[]

var tourneyData = {
    tName : tourneyName,
    tNum : number,
    'tNames[]' : names, // this is an array
    tInt : international,
    tLig : liga,
    tStars : stars
};

例子在这里找到: http://api.jquery.com/jQuery.post/

Examples found here: http://api.jquery.com/jQuery.post/

如果您要发送更复杂的对象或N维数组,你会想看看使用JSON。您可以使用 {对象:JSON.stringify(对象)} 在JS端和 json_parse($ _ POST ['对象'])在PHP端。

If you are sending more complex objects or n-dimensional arrays, you will want to look into using JSON. you can use {object: JSON.stringify(object)} on the JS side and json_parse($_POST['object']) on the PHP side.

这篇关于PHP无法读取阵列通过AJAX发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆