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

在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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题