javascript jQuery、AJAX、JSONP:即使数组为空,如何实际发送数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9397669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:31:53  来源:igfitidea点击:

jQuery, AJAX, JSONP: how to actually send an array even if it's empty?

javascriptjqueryjson

提问by

I've already read those questions but none of them answer to my need:

我已经阅读了这些问题,但没有一个能满足我的需要:

(the latest one said just add hard-coded quotes ie ['']but I can't do this, I'm calling a function that returns an Array)

(最新的一个说只是添加硬编码的引号,即['']但我不能这样做,我正在调用一个返回数组的函数)

So here's my code (note that the problem lies to the empty array new Array()):

所以这是我的代码(请注意,问题出在空数组上new Array()):

function AjaxSend() {
  $.ajax({
    url: '/json/myurl/',
    type: 'POST',
    dataType: 'jsonp',
    data : { 'tab':new Array() },
    context: this,
    success: function (data) {
      if (data.success) {
        console.log('ok');
      }   
      else {
        console.log('error');
      }   
    }   
  }); 
}

Simple eh? Here's my Php code:

简单吧?这是我的 PHP 代码:

echo '_POST='.var_export($_POST,true)."\n";

And here's the result:

结果如下:

_POST=array (
)
jQuery1710713708313414827_1329923973282(...)

If I change the empty Array by a non-empty, i.e.:

如果我将空数组更改为非空,即:

'tab':new Array({ 't':'u' },{ 'v':'w' })

The result is:

结果是:

_POST=array (
  'tab' => 
  array (
    0 => 
    array (
      't' => 'u',
    ),
    1 => 
    array (
      'v' => 'w',
    ),
  ),
)
jQuery1710640656704781577_1329923761425(...)

So this clearly means that when there's an empty Array() to be sent, it is ignored, and it's not added to the POST variables.

所以这显然意味着当要发送一个空的 Array() 时,它会被忽略,并且不会添加到 POST variables 中

Am I missing something?

我错过了什么吗?

PS: my jQuery version is from the latest google CDN i.e.:

PS:我的 jQuery 版本来自最新的谷歌 CDN,即:

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

and

http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js

http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js

I want the array to be sent, even if it's empty (= send [])! Any solution? Any idea? I've already tried to add this option traditional: truewithout success.

我想要发送数组,即使它是空的(= 发送[])!有什么解决办法吗?任何的想法?我已经尝试添加此选项traditional: true但没有成功。

采纳答案by PatrikAkerstrand

The problem is that you can't really send empty array. Have you tried to send an empty array manually? How would that uri look (note that it's the same reasoning for POST)?

问题是你不能真正发送空数组。您是否尝试过手动发送空数组?这个 uri 看起来如何(请注意,这与 POST 的推理相同)?

/path?arr[]

This would result in a $_GET like this:

这将导致 $_GET 像这样:

array (
 'arr' => array (
    0 => ''
  )
)

That's not really an empty array, is it? It's an array with a single element of an empty string. So what jQuery does, and I would agree that this is the correct way of handling it, is to not send anything at all.

那不是真正的空数组,是吗?它是一个包含一个空字符串元素的数组。所以 jQuery 所做的,我同意这是处理它的正确方法,是根本不发送任何东西。

This is actually really simple for you to check on the server. Just add an extra check whether the parameter exists or not, i.e:

这实际上对您在服务器上进行检查非常简单。只需添加一个额外的检查参数是否存在,即:

$tabs = array();
if(isset($_POST['tab'])) {
  $tabs = $_POST['tab'];
}

回答by guest271314

Try

尝试

php

php

<?php
// `echo.php`
if (isset($_POST["emptyArray"])) { 
  function arr() { 
    $request = $_POST["emptyArray"]; 
    if(is_array($request) && count($request) === 0) { 
      // do stuff
      echo $request;
    };
  };
  arr();
};

js

js

    $.post("echo.php", {"emptyArray":[]}
      , function (data, textStatus, jqxhr) {
          if (textStatus === "success" && data.length === 0) {
            // do stuff
            console.log(data.length === 0 ? new Error("error").message : data);
          };
    });

jsfiddle http://jsfiddle.net/guest271314/Lf6GG/

jsfiddle http://jsfiddle.net/guest271314/Lf6GG/