Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

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

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

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)."
";

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...