在jquery中发送多个数据

时间:2011-11-24 08:47:30

标签: php javascript jquery json

我有这个用于发送数据的代码

  var test={imagename:"apple.jpg",x:"13",y:"33"};

  $.ajax({
 type: "POST",
     url: "some.php",
     data: test,
     success: function(response){
    console.log(response);
    }
   });

但现在我想将多个数据发送到php.My php端代码就像这样

print $_POST['imagename'];

我想到了这样的方法  var test={imagename:"apple.jpg|hen.jpg",x:"13|44",y:"33|22"}; 并在php获取$_POST['imagename']然后根据|拆分它,但我不喜欢它的语义方法。
1 - 有没有人知道更好的解决方案?
2 - 请提供javascript,jquery和php代码以供回答 3-最后一个问题是这个名为json var test={imagename:"apple.jpg",x:"13",y:"33"};的符号 感谢

5 个答案:

答案 0 :(得分:7)

数组是最有意义的解决方案 - 在JavaScript中是这样的:

var data = [
    {imagename:"apple1.jpg", x:"13", y:"33"},
    {imagename:"apple2.jpg", x:"51", y:"84"},
    {imagename:"apple3.jpg", x:"79", y:"57"}
];

发送方式:

$.ajax({
     type: "POST",
     url: "some.php",
     data: {data: data},
     success: function(response){
         console.log(response);
     }
 });

在PHP中你可以得到它们:

<?
    print_r($_POST['data']); // dumps an array

    $filename1 = $_POST['data'][0]['filename']; // filename of item #1
?>

最后,var test={imagename:"apple.jpg",x:"13",y:"33"};只不过是一些JavaScript代码。它不是 JSON。虽然JSON看起来像JavaScript(JS甚至代表JSON中的JavaScript),但它只不过是你发送的字符。 JSON是一种传输数据的格式。一旦你“解压缩”它(用JavaScript或PHP),它就不再被称为JSON了。

答案 1 :(得分:3)

@pimvdb上的一点延伸:

foreach($_POST['data'] as $data) {
    $filename = $data['filename'];
    $width = $data['x'];
    $height = $data['y'];

    do_something_with_it($filename, $width, $height);
}

答案 2 :(得分:2)

您可以尝试使用嵌套对象,如下所示:

var test={imagename:["apple.jpg","hen.jpg"],x:["13","44"],y:["33","22"]};

  $.ajax({
     type: "POST",
     url: "some.php",
     data: test,
     success: function(response){
       console.log(response);
     }
  });

然后从PHP方面,您应该能够通过调用:

将其作为数组访问
  $_POST['image name'][index_num_here];

  Example:
  $_POST['image name'][0] => "apple.jpg"

答案 3 :(得分:2)

使用数组。 使用Javascript:

var data = {
    "images": [
          {name: "apple.jpg", x: 13, y:14},
          {name: "egg.jpg", x:14, y: 35}
    ]
};

$.ajax({
   type: "POST",
   url: "some.php",
   data: data,
   success: function(response){
     console.log(response);
   }
 });

PHP:

// First.
print $_POST['images'][0]['name'] // Prints apple.jpg
// Second
print $_POST['images'][1]['name'] // Prints egg.jpg

// Looping
foreach($_POST['images'] as $image) {
    print $image['name'];
    print $image['x'];
    print $image['y'];
}

来自你的例子

var test={imagename:"apple.jpg",x:"13",y:"33"};

以下部分被视为JSON(JavaScript Object Notation):

{imagename:"apple.jpg",x:"13",y:"33"}

每个JSON字符串也都是有效的JavaScript。

答案 4 :(得分:0)

我使用this取得了很大的成功,将JSON数据发送到服务器。它非常易于使用:

var test={imagename: ["apple.jpg", "banana.png"],x:"13",y:"33"};
$.post('some.php', {data: JSON.stringify(test)}, function(respons) { ... });

在服务器端,你有:

<?php
$data = json_decode(urldecode($_POST['json']), true);
echo $data['imagename'][0];
echo $data['imagename'][1];
?>
相关问题