【问题标题】:How to send arrays using XMLHttpRequest to server如何使用 XMLHttpRequest 将数组发送到服务器
【发布时间】:2012-08-23 17:19:16
【问题描述】:

据我所知,您可以使用 ajax 将数据发送到服务器,但我对使用 XMLHttpRequest 而不是像 jQuery 这样的任何库发送数组来发布感到困惑。我的问题是,是否可以使用XMLHttpRequest 将数组发送到php 以及jQuery 如何将数组发送到php,我的意思是jQuery 是否会做任何额外的工作来将数组发送到服务器(php $_POST ) ?

【问题讨论】:

    标签: jquery ajax xmlhttprequest


    【解决方案1】:

    嗯,除了一串字节,你不能发送任何东西。 “发送数组”是通过序列化(制作对象的字符串表示)数组并发送来完成的。 然后服务器将解析字符串并从中重新构建内存对象。

    所以将[1,2,3] 发送到 PHP 可能会像这样发生:

    var a = [1,2,3],
        xmlhttp = new XMLHttpRequest;
    
    xmlhttp.open( "POST", "test.php" );
    xmlhttp.setRequestHeader( "Content-Type", "application/json" );
    xmlhttp.send( '[1,2,3]' ); //Note that it's a string. 
                              //This manual step could have been replaced with JSON.stringify(a)
    

    test.php:

    $data = file_get_contents( "php://input" ); //$data is now the string '[1,2,3]';
    
    $data = json_decode( $data ); //$data is now a php array array(1,2,3)
    

    顺便说一句,使用 jQuery 你会这样做:

    $.post( "test.php", JSON.stringify(a) );
    

    【讨论】:

    • 谢谢。你能解释一下file_get_contents( "php://input" );吗?
    • @Red 它是请求正文的原始表示。见php.net/manual/en/wrappers.php.php。例如,考虑普通表单提交,您有$_POST["key"] === "value""php://input" 的内容在本例中为 "key=value",这是 PHP 用来为您构建 $_POST 数组的内容。你需要在这里使用它,因为在发布 JSON 时,php 不会填充 $_POST(因为 $_POST 仅适用于表单,不适用于 JSON)。
    • 那么当我使用$.post 时,我如何以$name=$_POST['name'] 获取数据?
    • @Red 不要将$.post$_POST 混淆。这完全取决于您$.post 的格式(从您的评论中不清楚)。 $_POST 仅适用于表单编码数据。像这样发布 JSON 时,需要从请求正文中手动解码。
    • 对不起,如果我误解了,但我的问题是当我使用$.post( "test.php", JSON.stringify(a) ); 时如何获取$_POST 中的数据?
    【解决方案2】:

    这取决于您选择打包数据结构的协议。最常用的两种是 XML 和 JSON。两者都有声明数组的方法:

    JSON:['one thing', 'another thing']

    XML:<things><thing name='one thing' /><thing name='another thing' /></things>

    两者都不需要服务器进行任何重大的额外工作。在许多情况下,它实际上会减少工作量,因为您不需要使用命名约定来区分它们。

    【讨论】:

      【解决方案3】:

      您想发送一个 JSON 对象(可以是一个数组)。如果您使用的是 php Send JSON data to PHP using XMLHttpRequest w/o jQuery,请检查这一点。

      更多关于json的信息:http://json.org/

      jQuery json 示例:JQuery and JSON

      【讨论】:

        【解决方案4】:

        另一种方式,如果你想使用 x-www-form-urlencoded 内容类型通过 AJAX 向 PHP 发送数据,你必须这样做:

        var array = [1, 2, 3];
        
        //variable to concat POST parameters
        var params = "";
        
        
        for(var i = 0; i < array.length; i++){
        
          params += "array[]=" + array[i] + "&";
        
        }
        
        //Remove the last char which is '&'
        params = params.substring(0, params.length -1);
        
        var http = new XMLHttpRequest();
        
        http.open("POST", "http://localhost/your_script.php");
        
        http.onload = function (){
        
            //if response status is OK
            if(http.status === 200){
          
                console.log(JSON.parse(http.response));
          
            }else{
          
                //handle response if status is not OK
          
            }
        
        };
        
        //set content type as x-www-form-urlencoded
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        //send the request with parameters
        http.send(params);//params = "array[]=1&array[]=2&array[]=3"
        

        你的脚本.php:

        <?php
        //check if index "array" on POST is defined
        if(isset($_POST["array"])){
        
            //write a JSON body
            echo json_encode(["message" => "Received"], JSON_FORCE_OBJECT);
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-15
          • 2023-03-21
          • 2012-06-13
          • 1970-01-01
          • 1970-01-01
          • 2020-11-24
          • 1970-01-01
          • 2014-01-31
          相关资源
          最近更新 更多