dongyan1993 2013-12-11 20:38
浏览 214
已采纳

在javascript .send函数中传递数组

This is regarding passing an array to a php page.Is it possible to send an array like this(code below)? if its not possible , what changes should i bring about to my code?

function ajax_post(){    
var hr = new XMLHttpRequest();    
hr.open("POST", "get_numbers.php", true);  
hr.setRequestHeader("Content-type", "application/json");    
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var data = JSON.parse(hr.responseText);
        var results=document.getElementById("ace");
        //results.innerHTML=data.u1.port;
        for (var obj in data)
       {
        results.innerHTML+=data[obj].port;
       }
    }
} 
var cards= new Array();
cards[0]="hearts";
cards[1]="spades";
hr.send(cards); 
results.innerHTML = "processing...";
}
  • 写回答

1条回答 默认 最新

  • dounao1856 2013-12-11 20:46
    关注

    .send() doesn't take a javascript array. There are a number of forms of data you could send and you will have to decide which form is appropriate, but an array is not one of them. The simplest would be to turn the array into a JSON string and send that.

    var cards = [
        "hearts",
        "spades"
    ];
    
    hr.send(JSON.stringify(cards)); 
    

    Then, on the receiving end of things, you would parse the JSON back into whatever language form you are using on the server end. If it's PHP, then you can use the PHP functions for parsing the JSON which will put the data into a PHP array on your server.

    Per the MDN doc page for the XMLHttpRequest object, .send() can take the following types of data:

    void send();
    void send(ArrayBufferView data);
    void send(Blob data);
    void send(Document data);
    void send(DOMString? data);
    void send(FormData data);
    

    Using JSON would be using the string type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器