【问题标题】:get data as an array using ajax post使用ajax post将数据作为数组获取
【发布时间】:2013-12-12 10:10:08
【问题描述】:

我有一个可以从 php 文件中获取数据的代码。 这里是:

function getMods(){
    var init;
    $.ajax({
    type: "POST",
    url: "init.php",
    data: { 'id': getID()},
    cache: false,
    success: function(data)
        {
            init = data;
        },
        async:false
    });
    return init;
}

这里是php文件:

<?php
include('dbconnect.php');
if(isset($_POST['id'])){
$id = $_POST['id'];
$value = "";
$init = array("Name","Owner","Admin1","Admin2","Admin3","Admin4");
for($i = 0; $i > 6;$i++){
$value[$i] = chatMods($init[$i],$id,$username,$password);
}
echo json_encode($value);
}
?>

php 文件发送的数据是一个字符串。我想发送一个字符串数组的数据。我该怎么做?

【问题讨论】:

  • $init 的值是多少?
  • 一个字符串。例如,“约翰”
  • 我想把它变成一个数组,比如 "John" => owner, "John2" => user1, "john3" => user2。

标签: php ajax post send


【解决方案1】:

如果你想从你的 PHP 发送一个数组,最好使用 json :

在您的 PHP 文件中:

$data = array('hello', 'world');
echo json_encode($data);

JS:

$.ajax({
type: "POST",
dataType: "json",  
url: "init.php",
data: { 'id': getID(), 'Name': name },
cache: false,
success: function(data)
    {
        console.log(data);
    },
    async:false
});

【讨论】:

  • console.log(data);可以是 init = data[''];?
  • 你可以像在初始代码中那样做 init = data 。现在 init 将有一个你想要的数组。使用 console.log 检查 init 的值,看看是否是你想要的。
  • 说“出了点问题”根本无济于事。将其包含在文件的开头:error_reporting(E_ALL|E_STRICT); ini_set('display_errors', true);
  • 我有一个未定义的值。
  • 那么你显示了错误的代码,因为你的变量被称为“值”,而不是“值”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
相关资源
最近更新 更多