dongyan1993
2013-12-11 20:38
浏览 142

在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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题