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

后端 未结 2 2039
别那么骄傲
别那么骄傲 2020-12-05 23:09

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 reques
相关标签:
2条回答
  • 2020-12-05 23:49

    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/

    0 讨论(0)
  • 2020-12-05 23:54

    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'];
    }
    
    0 讨论(0)
提交回复
热议问题