$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>javascript - jQuery, AJAX, JSONP: how to actually send an array even if it's empty? - Stack Overflow|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin23PV0评论

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

  • Testing for an empty array object in JSON with jQuery
  • jQuery 1.4.4+ AJAX request - post empty array or object becomes string
  • Cannot access data from jQuery Ajax request, returns empty array
  • JQuery removes empty arrays when sending

(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()):

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:

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.

Am I missing something?

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

.min.js

and

.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: true without success.

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

  • Testing for an empty array object in JSON with jQuery
  • jQuery 1.4.4+ AJAX request - post empty array or object becomes string
  • Cannot access data from jQuery Ajax request, returns empty array
  • JQuery removes empty arrays when sending

(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()):

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:

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.

Am I missing something?

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

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

and

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: true without success.

Share Improve this question edited May 23, 2017 at 11:54 CommunityBot 11 silver badge asked Feb 22, 2012 at 15:24 user292916user292916 2
  • 3 Have you thought about sending a separate variable containing the length of the array? When the length is zero, the array is empty. You can use this check rather than trying to account for the missing array variable in the post. – tvanfosson Commented Feb 22, 2012 at 15:32
  • @FelixKling You're right, that gives the same (abnormal) result. – user292916 Commented Feb 23, 2012 at 8:15
Add a comment  | 

2 Answers 2

Reset to default 20

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)?

/path?arr[]

This would result in a $_GET like this:

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.

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'];
}

Try

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

    $.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/

Post a comment

comment list (0)

  1. No comments so far